OGeek|极客世界-中国程序员成长平台

标题: ios - addChildViewController 给出 NSException 错误? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 10:14
标题: ios - addChildViewController 给出 NSException 错误?

我不熟悉使用这种方法,所以我可能完全错误,所以这是我的代码:

@property (nonatomic, weak) ConverterViewController *converterViewController;
@property (nonatomic, weak) CalculatorViewController *calculatorViewController;

如果我正确理解了这段代码,这些代码就是对两个不同 ViewController 的引用。

然后我的 viewDidAppear 方法中有这个:

[self addChildViewController:_converterViewController];
[_converterViewController didMoveToParentViewController:self];
[self.view addSubview:_converterViewController.view];

当我尝试将其添加为 subview Controller 时,我在第一行得到一个 NSException。所以不知道这是否应该在我的 ConverterViewController 类中调用一些方法,我在该类中放置了一些断点 initWithNibName 和 viewDidLoad 方法,我发现这些方法都没有被调用,所以我不完全确定出了什么问题。再说一次,我不太确定会出现什么问题,因此非常感谢任何帮助。

这就是我从控制台得到的全部信息:

libc++abi.dylib: terminating with uncaught exception of type NSException



Best Answer-推荐答案


更新答案:

[self addChildViewController:_converterViewController]; 不会创建 converterViewController
它只需要 converterViewController 对象并将其作为 childViewController 添加到 self

您需要在 -addChildViewController: 之前分配内存并实例化对象 converterViewController 否则它的值将是 nil 并且什么都不会发生.

所以...这样的事情:

_converterViewController = [[ConverterViewController alloc] initWithNibName"ConverterViewController"
                                                                     bundle:nil];

//now... adding it as childViewController should work
[self addChildViewController:_converterViewController];
[_converterViewController didMoveToParentViewController:self];
//optional: give it a frame explicitly so you may arrange more childViewControllers
//[_converterViewController.view setFrame:CGRectMake(0,0,100,100)];
[self.view addSubview:_converterViewController.view];

关于ios - addChildViewController 给出 NSException 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23982965/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4