Como usar o método parametrizado com NSNotificationCenter?
-
10-07-2019 - |
Pergunta
Eu gostaria de passar dict ao processit método. Mas uma vez eu acessar o dicionário, recebo 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];
No método destinatário:
- (void) processit: (NSDictionary *)name{
NSString *test = [name valueForKey:@"l"]; //EXC_BAD_INSTRUCTION occurs here
NSLog(@"output is %@", test);
}
Todas as sugestões sobre o que estou fazendo de errado?
Solução
Você receberá um objeto NSNotification, não um NSDictionary no callback notificação.
Tente isto:
- (void) processit: (NSNotification *)note {
NSString *test = [[note userInfo] valueForKey:@"l"];
NSLog(@"output is %@", test);
}
Outras dicas
Amrox é absolutamente certo.
Pode-se também usar objeto (em vez de userInfo) para o mesmo como abaixo:
- (void) processit: (NSNotification *)note {
NSDictionary *dict = (NSDictionary*)note.object;
NSString *test = [dict valueForKey:@"l"];
NSLog(@"output is %@", test);
}
Neste caso seu postNotificationName: objeto será algo como:
[[NSNotificationCenter defaultCenter] postNotificationName:@"atest" object:dict];
Você receberá um objeto NSNotification, não um NSDictionary no callback notificação.
-
(void) processit: (NSNotification *) nota {
NSDictionary dict = (NSDictionary ) note.object;
NSString * test = [Dict valueForKey: @ "l"];
NSLog (@ "saída é% @", test); }