首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSNotification不返回

NSNotification不返回
EN

Stack Overflow用户
提问于 2014-01-14 06:52:19
回答 1查看 183关注 0票数 0

我有一个模态UIViewController,上面有一个UITableView。对于用户选择的单元格,我希望将文本返回到前面的视图控制器,并取消模态视图。我使用NSNotifications将值发回。问题是,我的通知从未收到过。

下面是“父”视图中的代码:

代码语言:javascript
复制
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(choiceReceived:)
                                                 name:@"selectionMade"
                                               object:nil];

    [self performSegueWithIdentifier: @"locationsDetailsSegue" sender: self];
}

- (void) choiceReceived: (NSNotification *) notification
{
    NSLog(@"test");

    NSDictionary *dict = [notification userInfo];
    NSString *user_choice = [dict objectForKey:@"choice"];

    NSLog(@"%@", user_choice);

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: @"selectionMade"
                                                  object:nil];
}

在模态视图控制器中:

代码语言:javascript
复制
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    NSString *choice = cell.textLabel.text;

    // send a notification of this choice back to the 'parent' controller
    NSDictionary *dict = [NSDictionary dictionaryWithObject:choice forKey:@"choice"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"selectionMade" object:nil userInfo:dict];

    NSLog(@"%@", [dict objectForKey:@"choice"]);

    [self dismissViewControllerAnimated:YES completion:nil];
}

我从通知器得到正确的输出,但是我没有从接收方获得任何输出。我漏掉了什么明显的东西吗?谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-14 07:10:20

嗯,我不喜欢在这种情况下使用NSNotificationCenter (这只是我的建议)。在这种情况下,我总是推荐委托模式。委托模式工作或通信一对一的对象通知,因此它提供100%的精确输出和消除其他冲突。

在子视图控制器中创建协议方法,并委托属性在parentclassviewcontroller中进行确认。在parentviewcontroller中使用chileviewcontroller协议。在parentviewcontroller类中实现所需的协议委托方法。此外,还可以通过委托方法发送多种类型的参数。要获得更多信息,请访问此文档

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21107543

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档