如何在NSNotificationCenter中使用参数化方法?

时间:2009-06-23 21:18:22

标签: objective-c iphone cocoa-touch nsnotifications

我想将dict传递给方法processit。但是一旦我访问字典,我就得到了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];

在收件人方法中:

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

有关我做错的任何建议吗?

3 个答案:

答案 0 :(得分:17)

您将在通知回调中收到NSNotification对象,而不是NSDictionary。

试试这个:

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

答案 1 :(得分:2)

Amrox绝对正确。

也可以使用Object(而不是userInfo),如下所示:

- (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];

答案 2 :(得分:0)

您将收到NSNotification对象,而不是通知回调中的NSDictionary。

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

    NSDictionary dict =(NSDictionary )note.object;

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

    NSLog(@“输出为%@”,测试); }