7

我想将 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);
}

关于我做错了什么有什么建议吗?

4

3 回答 3

17

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

试试这个:

- (void) processit: (NSNotification *)note {
    NSString *test = [[note userInfo] valueForKey:@"l"];
    NSLog(@"output is %@", test);
}
于 2009-06-23T21:34:06.550 回答
2

Amrox 是绝对正确的。

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

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

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

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

在这种情况下,您的 postNotificationName:object 将如下所示:

[[NSNotificationCenter defaultCenter] postNotificationName:@"atest" object:dict];
于 2011-05-19T06:43:33.440 回答
0

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

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

    NSDictionary dict = (NSDictionary )note.object;

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

    NSLog(@"输出为 %@", test); }

于 2013-11-28T12:08:16.877 回答