NSNotification没有返回

时间:2014-01-14 06:52:19

标签: ios objective-c nsnotifications

我有一个模式UIViewController,上面有UITableView。对于用户选择的任何单元格,我想将该文本返回到前一个视图控制器并关闭模态视图。我正在使用NSNotifications将值发回。问题是,我的通知从未收到过。

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

- (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];
}

在模态视图控制器中:

- (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];
}

我从通知程序得到了正确的输出,但我从接收器中得不到任何输出。我错过了一些明显的东西吗谢谢!

1 个答案:

答案 0 :(得分:4)

好吧,我不喜欢在这种情况下使用NSNotificationCenter仅仅是我的建议)。在这种情况下,我总是建议委托模式。委托模式工作或传达一对一的对象通知,以便提供100%精确的输出并消除其他冲突 在childviewcontroller中创建协议方法,并在parentclassviewcontroller中委托属性以进行确认。 在parentviewcontroller中使用chileviewcontroller协议。在parentviewcontroller类中实现所需的协议委托方法。您还可以通过委托方法发送多种类型的参数。 欲了解更多信息,请查看doc