当我使用prepareForSegue将值传递给目标控制器时,存在一些问题

首先,我使用storyboard创建两个uiviewcontroller: firstviewcontrollersecondviewcontroller 。 并使用xcode将uinavigationcontroller嵌入到secondviewcontroller中 (编辑器 – >嵌入 – >导航控制器) 。 然后,我还想使用segue将值从第一个传递到第二个。 有代码:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if([segue.identifier isEqualToString:@"passValue"]) { secondViewController *saveViewController = [segue destinationViewController]; [saveViewController setValue:data forKey:@"data"]; } } 

但是会报告错误,日志是: 由于未捕获的exception’NSUnknownKeyException’终止应用程序,原因:'[setValue:forUndefinedKey:]:此类不是密钥数据的密钥值编码兼容。

但是,当我删除导航控制器,我使用Xcode插入它并按代码定义导航栏时,此问题将消失。 我想原因是真正的destinationViewController是navigationcontroller而不是secondviewcontroller 。 因此,如果我想保留Xcode嵌入的导航控制器,如何解决这个问题呢?

你是对的, destinationViewController将是你嵌入了secondViewControllerUINavigationController 。也许试试看:

 secondViewController *saveViewController = [[segue destinationViewController] topViewController];