2009-06-23 17 views
7

我想將字典傳遞給方法processit。但是一旦我訪問字典,就會得到EXC__BAD_INSTRUCTION。如何在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]; 

在收件人方法:

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

什麼,我做錯了什麼建議?

回答

17

您將收到NSNotification對象,而不是通知回調中的NSDictionary。

試試這個:

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

Amrox是絕對正確的。

你也可以使用對象(而不是用戶信息)爲同一如下:

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

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

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

在這種情況下,你postNotificationName:物體的樣子:

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

謝謝阿德里安更新代碼。從下次開始,我會照顧格式化。 :) – 2011-06-10 10:45:26

0

,您會收到NSNotification對象,而不是通知回調中的NSDictionary。

  • (無效)方法processIt:(NSNotification *)注{

    的NSDictionary 字典=(的NSDictionary)note.object;

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

相關問題