ios - 使用 popToRootViewController 传递数据

标签 ios objective-c uistoryboardsegue rootview poptoviewcontroller

所以我有一个基本的应用程序,下面是它的工作原理。我有一个名为 A 的 Root View Controller 和一个名为 B 的 TableView Controller 。当用户在 B 中选择一行时,我会弹回 Root View Controller A。

我想做的是将被选为 NSString 的行的数据传递回 Root View Controller A。然后使用此字符串根据字符串“做某事”。

我曾尝试使用 NSNotification 方法,但后来我无法使用该字符串做某事。

这是我尝试过的:

//tableViewB.m
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"passData" object:[[_objects objectAtIndex:indexPath.row] objectForKey:@"title"]];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
//rootViewA.m
-(void)dataReceived:(NSNotification *)noti
{
     NSLog(@"dataReceived :%@", noti.object);

}
-(void)viewDidLoad {
  [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataReceived:) name:@"passData" object:nil];
}

我想做的是更像您在推送 viewController 并使用 perpareForSegue 方法时可以做的事情。

预先感谢您的帮助。

最佳答案

您正在做正确的事情,但使用了错误的参数。通知帖子中的 object: 参数是发送对象。还有另一个 post 方法允许调用者附加 userInfo:,如下所示:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    // notice the prettier, modern notation
    NSString *string = _objects[indexPath.row][@"title"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"passData"
                                                        object:self
                                                      userInfo:@{"theString" : string }]
    [self.navigationController popToRootViewControllerAnimated:YES];
}

在接收端,只需使用相同的 key 从通知的用户信息中获取数据:

-(void)dataReceived:(NSNotification *)notification {

     NSLog(@"dataReceived :%@", notification.userInfo[@"theString"]);
}

关于ios - 使用 popToRootViewController 传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23902357/

相关文章:

objective-c - 构建具有相同核心的多个应用程序

ios - 如何在用户点击右侧栏按钮项目时显示弹出窗口?

ios - 如何从多个导航 Controller 切换到一个 View Controller ,并在完成后返回到 swift 呈现的任何一个 View Controller

ios - 执行从 tableview 到 viewcontroller 的 segue 时出现问题

ios - UITableView 数据源方法的奇怪行为

ios - 无法将文件复制到 Xcode 中的产品目录

php - APNS 多个 registerId

html - 防止缩放移动网站不起作用

ios - 我必须将什么拖到哪里才能通过点击背景关闭键盘?

ios - 以编程方式设置 RGB