Как использовать параметризованный метод с NSNotificationCenter?
-
10-07-2019 - |
Вопрос
Я бы хотел передать dict методу processit.Но как только я получаю доступ к словарю, я получаю ИНСТРУКЦИЮ EXC__BAD_.
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);
}
Есть какие-нибудь предложения относительно того, что я делаю не так?
Решение
Вы получите объект NSNotification, а не NSDictionary в обратном вызове уведомления. Р>
Попробуйте это:
- (void) processit: (NSNotification *)note {
NSString *test = [[note userInfo] valueForKey:@"l"];
NSLog(@"output is %@", test);
}
Другие советы
Amrox абсолютно прав.
Можно также использовать Object (вместо userInfo) для того же, что и ниже:
- (void) processit: (NSNotification *)note {
NSDictionary *dict = (NSDictionary*)note.object;
NSString *test = [dict valueForKey:@"l"];
NSLog(@"output is %@", test);
}
В этом случае ваш postNotificationName: object будет выглядеть следующим образом:
[[NSNotificationCenter defaultCenter] postNotificationName:@"atest" object:dict];
Вы получите объект NSNotification, а не NSDictionary в обратном вызове уведомления.
(недействительный) процесс:(NSNotification *)примечание {
Справочник dict = (NSDictionary)примечание.объект;
NSString *test = [указать valueForKey:@"l"];
NSLog(@"вывод равен %@", тест);}