目标C:发送到实例0xba3e750的无法识别的选择器

我编写了这段代码,当我运行程序时,它会抛出异常:无法识别的选择器发送到实例0xba3e750

storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    navigationController = [storyboard instantiateViewControllerWithIdentifier:@"SecondViewID"];
    selected = navigationController.viewControllers[0];

当我把这一行放在评论中

//selected = navigationController.viewControllers[0];

像这样,程序不会抛出异常 . 这是洞例外

2014-06-12 20:59:44.749 passing image[2194:a0b] -[SecondViewController viewControllers]: unrecognized selector sent to instance 0xba3e750

2014-06-12 20:59:44.753传递图像[2194:a0b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SecondViewController viewControllers]: unrecognized selector sent to instance 0xba3e750' *** 第一次抛出调用堆栈:(0 CoreFoundation 0x017445e4 exceptionPreprocess + 180 1 libobjc.A.dylib 0x014c78b6 objc_exception_throw + 44 2 CoreFoundation 0x017e1903 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275 3 CoreFoundation 0x0173490b __forwarding 1019 4 CoreFoundation 0x017344ee _CF_forwarding_prep_0 14 5传递图像0x000056a2 - [ViewController viewDidLoad] 466 6 UIKit 0x00349318 - [UIViewController loadViewIfRequired] 696 7 UIKit 0x003495b4 - [UIViewController视图] 35 8 UIKit 0x002719fd - [UIWindow addRootViewControllerViewIfPossible] 66 9 UIKit 0x00271d97 - [UIWindow _setHidden:forced:] 312 10 UIKit 0x0027202d - [UIWindow _orderFrontWithoutMakingKey] 49 11 UIKit 0x0027c89a - [UIWindow makeKeyAndVisible] 65 12 UIKit 0x0022fcd0 - [UIApplication _callInitializationDelegatesForURL:payload:suspended:] 1851 13 UIKit 0x002343a8 - [UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] 824 14 UIKit 0x0024887c - [UIApplication handleEvent:withNewEvent:] 3447 15 UIKit 0x00248de9 - [ UIApplication sendEvent:] 85 16 UIKit 0x00236025 _UIApplicationHandleEvent 736 17 G raphicsServices 0x037932f6 _PurpleEventCallback 776个18 GraphicsServices 0x03792e01 PurpleEventCallback 46 19的CoreFoundation 0x016bfd65 CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION 53 20的CoreFoundation 0x016bfa9b __CFRunLoopDoSource1 523 21的CoreFoundation 0x016ea77c __CFRunLoopRun 2156 22的CoreFoundation 0x016e9ac3 CFRunLoopRunSpecific 467 23的CoreFoundation 0x016e98db CFRunLoopRunInMode 123 24的UIKit 0x00233add - [UIApplication的_run] 840 25的UIKit 0x00235d3b UIApplicationMain 1225 26通过image 0x0000750d main 141 27 libdyld.dylib 0x01e78725 start 0 28 ??? 0x00000001 0x0 1)libc abi.dylib:以NSException(lldb)类型的未捕获异常终止

回答(1)

2 years ago

instantiateViewControllerWithIdentifier: 返回 UIViewController ,但是当你不应该将它存储在 UINavigationController 中 . 当您尝试访问 UINavigationController 属性( viewControllers )时,它崩溃了,因为 UIViewController 没有名为 viewControllers 的属性 .

尝试将方法 instantiateViewControllerWithIdentifier: 的返回存储在 UIViewController 而不是 UINavigationController 中:

UIViewController * viewController = [storyboard instantiateViewControllerWithIdentifier:@"SecondViewID"];
selected = viewController.navigationController.viewControllers[0];