How to use a parameterized method with NSNotificationCenter?

I want to pass a dict to the processit method. But as soon as I get access to the dictionary, I get EXC__BAD_INSTRUCTION.

NSNotificationCenter *ncObserver = [NSNotificationCenter defaultCenter]; [ncObserver addObserver:self selector:@selector(processit:) name:@"atest" object:nil]; NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"testing", @"first", nil]; NSString *test = [dict valueForKey:@"first"]; NSNotificationCenter *ncSubject = [NSNotificationCenter defaultCenter]; [ncSubject postNotificationName:@"atest" object:self userInfo:dict]; 

In the recipient method:

 - (void) processit: (NSDictionary *)name{ NSString *test = [name valueForKey:@"l"]; //EXC_BAD_INSTRUCTION occurs here NSLog(@"output is %@", test); } 

Any suggestions on what I'm doing wrong?

+7
objective-c iphone cocoa-touch nsnotifications
source share
3 answers

You will get an NSNotification object, not an NSDictionary in the notification callback.

Try the following:

 - (void) processit: (NSNotification *)note { NSString *test = [[note userInfo] valueForKey:@"l"]; NSLog(@"output is %@", test); } 
+17
source share

Amrox is absolutely right.

You can also use Object (instead of userInfo) for the same as below:

 - (void) processit: (NSNotification *)note { NSDictionary *dict = (NSDictionary*)note.object; NSString *test = [dict valueForKey:@"l"]; NSLog(@"output is %@", test); } 

In this case, your postNotificationName: object will look like this:

 [[NSNotificationCenter defaultCenter] postNotificationName:@"atest" object:dict]; 
+2
source share

You will get an NSNotification object, not an NSDictionary in the notification callback.

  • (void) processit: (NSNotification *) note {

    NSDictionary dict = (NSDictionary) note.object;

    NSString * test = [dict valueForKey: @ "l"];

    NSLog (exit "@" -% @ ", test);}

0
source share

All Articles