起因:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, 100, 100);
button.backgroundColor = [UIColor redColor];
[self.view addSubview:button];
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)buttonAction:(UIButton *)button
{
//添加界面
NDTSecondViewController *secondViewController = [[NDTSecondViewController alloc] init];
// [self addChildViewController:secondViewController];
[self.view addSubview:secondViewController.view];
// [secondViewController didMoveToParentViewController:self];
}
在firstviewcontroller上添加secondViewController
[secondviewcontroller.view removeFromSuperview];的时候,程序奔溃
原因分析:
当添加secondviewController.view的时候,
系统增加啦viewcontroll的属性view的引用计数,减少啦secondviewcontroller的引用计数,此时:
NDTSecondViewController delloc
viewcontrolller 已经释放,
当secondviewcontroller.view removeFromSuperview];的时候,系统减少view的引用计数,同时减少viewcontroller的引用计数,崩溃;
解决办法:
把viewcontroller当做容器的时候
[self addChildViewController:secondViewController];
[self.view addSubview:secondViewController.view];
[secondViewController didMoveToParentViewController:self];
先把secondviewcontroller添加到容器中。。。。
当secondviewcontroller移除的时候
//删除界面
[self.viewremoveFromSuperview];
[selfremoveFromParentViewController];
此时:secondviewController会自动释放
系统会自动调用: [secondViewController didMoveToParentViewController:nil];
无需手动调用,详情见官方文档
当使用下面这种方式的时候, secondViewController dismiss的时候,secondViewController会自动释放;
[selfpresentViewController:secondViewControlleranimated:YEScompletion:^{
NSLog(@"complete");
}];
[selfdismissViewControllerAnimated:YEScompletion:^{}];
nav push ,pop同上
添加:
当一个全屏的viewcontroller A想要添加一个size 大小为300 300 的viewController的时候 ,用上述方法也是可以的,而且不影响viewController的生命周期
代码如下:
NDTSecondViewController *secondViewController = [[NDTSecondViewController alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:secondViewController];
secondViewController.view.frame = CGRectMake(0, 0, 500, 500);
// secondViewController.view.frame = CGRectMake(0, 0, 500, 500);
[self addChildViewController:secondViewController];
[self.view addSubview:secondViewController.view];
[nav didMoveToParentViewController:self];
三、当childviewcontroller.view添加在containercontroller.view的子视图上的时候,会不会有啥内存或其他方面的问题呢?
验证:
//添加界面
NDTSecondViewController *secondViewController = [[NDTSecondViewController alloc] init];
secondViewController.view.frame = self.smallView.bounds;
[self addChildViewController:secondViewController];
[self.smallView addSubview:secondViewController.view];
[secondViewController didMoveToParentViewController:self];
答案:不影响生命周期,内存规则同上述一致;