未从Modal ViewController接收NSNotification

时间:2014-01-08 03:04:10

标签: ios objective-c nsnotificationcenter

我在这里缺少什么?我只是试图从模态视图控制器发送一个简单的通知回到启动它的视图控制器,但没有收到任何信息。

这是视图控制器中启动模态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

因此,选择被捕获并添加到字典中。但没有证据表明收到任何通知。这不是那么难,但我没有看到我的错误。有人能帮我吗?谢谢!

1 个答案:

答案 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];

参阅:https://stackoverflow.com/a/8188759/2449268