我在这里缺少什么?我只是试图从模态视图控制器发送一个简单的通知回到启动它的视图控制器,但没有收到任何信息。
这是视图控制器中启动模态segue的代码:
- (IBAction) chooseSuperGroup:(UIButton *)sender {
NSLog(@"super group choice about to be made");
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(choiceReceived:)
name:@"selectionMade"
object:self];
}
- (void) choiceReceived: (NSNotification *) notification
{
NSLog(@"here");
if ([[notification name] isEqualToString:@"selectionMade"]) {
NSLog(@"received");
NSLog(@"%@", (NSString *)[notification userInfo]);
}
[[NSNotificationCenter defaultCenter] removeObserver:self
name: @"selectionMade"
object:self];
}
然后,在模态视图控制器中,当用户从表视图中选择一个单元格时,将执行此代码:
NSDictionary *dict = [NSDictionary dictionaryWithObject:selection forKey:@"superGroup"];
NSLog(@"printing dictionary contents");
for (id key in dict) {
NSLog(@"key: %@ object: %@", key, [dict objectForKey:key]);
}
[[NSNotificationCenter defaultCenter] postNotificationName:@"selectionMade" object:self userInfo:dict];
我的输出如下:
Super group choice about to be made
printing dictionary contents
key: superGroup object: myChoice
因此,选择被捕获并添加到字典中。但没有证据表明收到任何通知。这不是那么难,但我没有看到我的错误。有人能帮我吗?谢谢!
答案 0 :(得分:4)
尝试使用'nil'代替'self'
//添加观察者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(choiceReceived:) name:@"selectionMade" object:nil];
//删除观察者
[[NSNotificationCenter defaultCenter] removeObserver:self
name: @"selectionMade"
object:nil];
//发布通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"selectionMade" object:nil userInfo:dict];