How to use parametrized method with NSNotificationCenter?
Asked Answered
F

3

7

I'd like to pass dict to the method processit. But once I access 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?

Floss answered 23/6, 2009 at 21:18 Comment(0)
S
17

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

Try this:

- (void) processit: (NSNotification *)note {
    NSString *test = [[note userInfo] valueForKey:@"l"];
    NSLog(@"output is %@", test);
}
Swahili answered 23/6, 2009 at 21:34 Comment(0)
F
2

Amrox is absolutely right.

One 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:

[[NSNotificationCenter defaultCenter] postNotificationName:@"atest" object:dict];
Filicide answered 19/5, 2011 at 6:43 Comment(1)
Thanks Adrian to update the code. I will take care of formatting also, from next time. :)Filicide
P
0

You will receive 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(@"output is %@", test); }

Peach answered 28/11, 2013 at 12:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.