Cocoa NSNotificationCenter communication between apps failed
I need to communicate between two different console apps, Observer and Client.
In the Observer app I added this code:
[[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:self];
In the Client app I added this code:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(trackNotification:) name:@"MyNotification" object:nil];
-(void)trackNotification:(NSNotification*)notif
{
NSLog(@"trackNotification: %@", notif);
NSLog(@"trackNotification name: %@", [notif name]);
NSLog(@"trackNotification object: %@", [notif object]);
NSLog(@"trackNotification userInfo: %@", [notif userInfo]);
}
but nothing happens. I read all the documentation, but I am brand new in Mac OS X. Any ideas?
I read about the Distributed Noti开发者_开发知识库fications, I changed my code and now looks like this: In the server side:
[[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(trackNotification:) name:@"MyNotification" object:nil];
-(void)trackNotification:(NSNotification*)notif
{
NSLog(@"trackNotification: %@", notif);
NSLog(@"trackNotification name: %@", [notif name]);
NSLog(@"trackNotification object: %@", [notif object]);
NSLog(@"trackNotification userInfo: %@", [notif userInfo]);
}
In the client side:
NSMutableDictionary *info;
info = [NSMutableDictionary dictionary];
[info setObject:@"foo" forKey:@"bar"];
[[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"MyNotification"
object:nil
userInfo:info
deliverImmediately:YES];
I run both applications, but nothing happens. What am I doing wrong?
NSNotificationCenter
is only for notifications within one app. You want NSDistributedNotificationCenter. You can find more details in the Notification Programming Topics.
I solved my problem. This is the source code: In the client side:
NSDictionary *user = [NSDictionary dictionaryWithObjectsAndKeys: @"John Doe", @"name", @"22222222222", @"phone", @"Dummy address", @"address", nil];
//Post the notification
NSString *observedObject = @"com.test.net";
NSDistributedNotificationCenter *center = [NSDistributedNotificationCenter defaultCenter];
[center postNotificationName: @"Plugin Notification" object: observedObject userInfo: user deliverImmediately: YES];
In the server side
NSString *observedObject = @"com.test.net";
NSDistributedNotificationCenter *center = [NSDistributedNotificationCenter defaultCenter];
[center addObserver: self selector: @selector(receiveNotification:) name: @"Plugin Notification" object: observedObject];
receiveNotification definition
-(void)receiveNotification:(NSNotification*)notif
{
NSlog(@"Hello");
}
In dealloc method
[[NSDistributedNotificationCenter defaultCenter] removeObserver:self name: @"Plugin Notification" object: nil];
精彩评论