OStack程序员社区-中国程序员成长平台

标题: ios - 未从模态视图 Controller 收到 NSNotification [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 05:55
标题: ios - 未从模态视图 Controller 收到 NSNotification

我在这里缺少什么?我只是想从模态视图 Controller 向启动它的 View Controller 发送一个简单的通知,但什么也没有收到。

这是 View Controller 中启动模态转场的代码:

- (IBAction) chooseSuperGroupUIButton *)sender {
    NSLog(@"super group choice about to be made");

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selectorselector(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];
}

然后,在模态视图 Controller 中,当用户从表格 View 中选择一个单元格时,将执行此代码:

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

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



Best Answer-推荐答案


尝试使用“nil”而不是“self”

//添加观察者

   [[NSNotificationCenter defaultCenter] addObserver:self selectorselector(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

关于ios - 未从模态视图 Controller 收到 NSNotification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20986243/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4