Как использовать параметризованный метод с NSNotificationCenter? - PullRequest
7 голосов
/ 24 июня 2009

Я бы хотел передать dict методу processit. Но как только я получаю доступ к словарю, я получаю 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];

В методе получателя:

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

Какие-либо предложения о том, что я делаю неправильно?

Ответы [ 3 ]

17 голосов
/ 24 июня 2009

Вы получите объект NSNotification, а не NSDictionary в обратном вызове уведомления.

Попробуйте это:

- (void) processit: (NSNotification *)note {
    NSString *test = [[note userInfo] valueForKey:@"l"];
    NSLog(@"output is %@", test);
}
2 голосов
/ 19 мая 2011

Амрокс абсолютно прав.

Можно также использовать Object (вместо userInfo) для того же, что и ниже:

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

    NSDictionary *dict = (NSDictionary*)note.object;

    NSString *test = [dict valueForKey:@"l"];
    NSLog(@"output is %@", test);
}

В этом случае ваш postNotificationName: объект будет выглядеть так:

[[NSNotificationCenter defaultCenter] postNotificationName:@"atest" object:dict];
0 голосов
/ 28 ноября 2013

Вы получите объект NSNotification, а не NSDictionary в обратном вызове уведомления.

  • (недействительно) processit: (NSNotification *) note {

    NSDictionary dict = (NSDictionary ) note.object;

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

    NSLog (@ "output is% @", test); }

...