如何在 NSNotificationCenter 中使用参数化方法?
我想将 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);
}
对我做错了什么有什么建议吗?
I'd like to pass dict to the method processit. But once I access the dictionary, I get 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];
In the recipient method:
- (void) processit: (NSDictionary *)name{
NSString *test = [name valueForKey:@"l"]; //EXC_BAD_INSTRUCTION occurs here
NSLog(@"output is %@", test);
}
Any suggestions on what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将在通知回调中收到一个 NSNotification 对象,而不是 NSDictionary。
尝试这个:
You will receive an NSNotification object, not an NSDictionary in the notification callback.
Try this:
Amrox 是绝对正确的。
还可以使用 Object(而不是 userInfo)进行如下操作:
在这种情况下,您的 postNotificationName:object 将如下所示:
Amrox is absolutely right.
One can also use Object (instead of userInfo) for the same as below:
In this case your postNotificationName:object will look like:
您将在通知回调中收到一个 NSNotification 对象,而不是 NSDictionary。
(void)processit:(NSNotification *)注意{
NSDictionary dict = (NSDictionary)note.object;
NSString *test = [dict valueForKey:@"l"];
NSLog(@"输出为%@",测试);
( void
You will receive an NSNotification object, not an NSDictionary in the notification callback.
(void) processit: (NSNotification *)note {
NSDictionary dict = (NSDictionary)note.object;
NSString *test = [dict valueForKey:@"l"];
NSLog(@"output is %@", test);
}