如何在 NSNotificationCenter 中使用参数化方法?
-
10-07-2019 - |
题
我想将 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);
}
关于我做错了什么有什么建议吗?
解决方案
您将在通知回调中收到NSNotification对象,而不是NSDictionary。
试试这个:
- (void) processit: (NSNotification *)note {
NSString *test = [[note userInfo] valueForKey:@"l"];
NSLog(@"output is %@", test);
}
其他提示
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];
您将在通知回调中收到一个 NSNotification 对象,而不是 NSDictionary。
(无效)处理:(NSNotification *)注意{
NS词典 字典 = (NSDictionary)注释.对象;
NSString *test = [dict valueForKey:@"l"];
NSLog(@"输出为%@",测试);}
不隶属于 StackOverflow