Comment utiliser la méthode paramétrée avec NSNotificationCenter?
-
10-07-2019 - |
Question
Je voudrais passer dict à la méthode processit. Mais une fois que j'accède au dictionnaire, j'obtiens 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];
Dans la méthode du destinataire:
- (void) processit: (NSDictionary *)name{
NSString *test = [name valueForKey:@"l"]; //EXC_BAD_INSTRUCTION occurs here
NSLog(@"output is %@", test);
}
Des suggestions sur ce que je fais mal?
La solution
Vous recevrez un objet NSNotification, et non un NSDictionary dans le rappel de notification.
Essayez ceci:
- (void) processit: (NSNotification *)note {
NSString *test = [[note userInfo] valueForKey:@"l"];
NSLog(@"output is %@", test);
}
Autres conseils
Amrox a absolument raison.
On peut aussi utiliser Object (au lieu de userInfo) pour les mêmes choses que ci-dessous:
- (void) processit: (NSNotification *)note {
NSDictionary *dict = (NSDictionary*)note.object;
NSString *test = [dict valueForKey:@"l"];
NSLog(@"output is %@", test);
}
Dans ce cas, l'objet postNotificationName: ressemblera à:
[[NSNotificationCenter defaultCenter] postNotificationName:@"atest" object:dict];
Vous recevrez un objet NSNotification, et non un NSDictionary dans le rappel de notification.
-
(void) processit: (NSNotification *) note {
NSDictionary dict = (NSDictionary ) note.object;
NSString * test = [dict valeurForKey: @ "l"];
NSLog (@ "la sortie est% @", test); }