所以我有一个基本的应用程序,下面是它的工作原理。我有一个名为 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/