Come utilizzare il metodo con parametri con NSNotificationCenter?
-
10-07-2019 - |
Domanda
Vorrei passare dict al metodo processit. Ma una volta che accedo al dizionario, ottengo 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];
Nel metodo destinatario:
- (void) processit: (NSDictionary *)name{
NSString *test = [name valueForKey:@"l"]; //EXC_BAD_INSTRUCTION occurs here
NSLog(@"output is %@", test);
}
Qualche suggerimento su cosa sto facendo di sbagliato?
Soluzione
Riceverai un oggetto NSNotification, non un NSDictionary nel callback di notifica.
Prova questo:
- (void) processit: (NSNotification *)note {
NSString *test = [[note userInfo] valueForKey:@"l"];
NSLog(@"output is %@", test);
}
Altri suggerimenti
Amrox ha assolutamente ragione.
Si può anche usare Object (invece di userInfo) per lo stesso di seguito:
- (void) processit: (NSNotification *)note {
NSDictionary *dict = (NSDictionary*)note.object;
NSString *test = [dict valueForKey:@"l"];
NSLog(@"output is %@", test);
}
In questo caso l'oggetto postNotificationName: sarà simile a:
[[NSNotificationCenter defaultCenter] postNotificationName:@"atest" object:dict];
Riceverai un oggetto NSNotification, non un NSDictionary nel callback di notifica.
-
(vuoto) processit: (NSNotification *) note {
NSDictionary dict = (NSDictionary ) note.object;
NSString * test = [dict valueForKey: @ " l "];
NSLog (@ "l'output è% @", test); }