2009-06-23 9 views
7

Je voudrais passer dict à la méthode processit. Mais une fois que j'accède au dictionnaire, j'obtiens EXC__BAD_INSTRUCTION.Comment utiliser la méthode paramétrée avec NSNotificationCenter?

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 bénéficiaire:

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

Toutes les suggestions sur ce que je fais mal?

Répondre

17

Vous recevrez un objet NSNotification, pas un NSDictionary dans le rappel de notification.

Essayez ceci:

- (void) processit: (NSNotification *)note { 
    NSString *test = [[note userInfo] valueForKey:@"l"]; 
    NSLog(@"output is %@", test); 
} 
2

Amrox est tout à fait raison.

On peut également utiliser l'objet (au lieu de userInfo) pour la même chose que ci-dessous:

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

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

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

Dans ce cas, votre postNotificationName: objet ressemblera:

[[NSNotificationCenter defaultCenter] postNotificationName:@"atest" object:dict]; 
+0

Merci Adrian pour mettre à jour le code. Je prendrai soin du formatage aussi, de la prochaine fois. :) –

0

Vous recevrez un NSNotification objet, pas un NSDictionary dans le rappel de notification.

  • (void) ProcessIt: (NSNotification *) Note {

    NSDictionary dict = (NSDictionary) note.object;

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

    NSLog (@ "sortie est% @", test); }

Questions connexes