一个孩子的视图控制器可以自动关闭吗? …..
你有一个视图控制器“RedMessage”.你有一个普通的强大财产…
@property(强)RedMessage *红色;
您添加它(“模态”)在您当前的VC …
self.red = (RedMessage *)[self.storyboard instantiateViewControllerWithIdentifier:@"RedMessageID"]; self.red.view.frame = self.view.frame; [self.view addSubview:self.red.view]; [self addChildViewController:self.red]; [self.red didMoveToParentViewController:self];
为了摆脱它以后,这样做
[self.red willMoveToParentViewController:nil]; [self.red.view removeFromSuperview]; [self.red removeFromParentViewController];
但实际上,你需要这样做吗?
[rm willMoveToParentViewController:nil]; [rm.view removeFromSuperview]; [rm removeFromParentViewController]; rm = nil;
你需要“= nil”吗?
请注意,这个问题是至关重要的,因为:如果您没有将其删除,则可以在新的视图控制器中执行以下操作:
-(void)dismissMyselfCompletely { [self willMoveToParentViewController:nil]; [self.view removeFromSuperview]; [self removeFromParentViewController]; }
这是非常方便的.
简而言之,如果你在新的顶视图控制器里面这样做 – 它会“工作”,它是否释放VC?
当removeFromParentViewController发生时,父VC了解它可以释放self.red吗?
解决方法
经过相当大的测试,我们发现似乎是这样的情况:
您实际上可以让VC“自己删除”.
它会消失,不会保留.
我们将VC顶部添加到这个顶部(只是在通常的方式你添加一个“模态”VC顶部…)
-(void)showOverlay:(NSDictionary*)dict { Red *rr = (Red *)[self.storyboard instantiateViewControllerWithIdentifier:@"RedID"]; rr.view.frame = self.view.bounds; [self.view addSubview:rr.view]; [self addChildViewController:rr]; [rr didMoveToParentViewController:self]; [rr useThisData:dict]; }
注意,没有属性持有rr – 它刚刚创建并在该类别中即时添加.
里面的“红”我们摆脱它就像这样…
-(void)dismiss:(UITapGestureRecognizer *)sender { [self.view exitLeftSmoothly:0 then:^ { [self willMoveToParentViewController:nil]; [self.view removeFromSuperview]; [self removeFromParentViewController]; }]; }
(exitLeft只是一个动画,不相关)
最后你可以这样测试:
-(void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; .... [self _teste]; } -(void)_teste { Red __weak *mySelf = self; dispatch_after_secs_on_main(0.5,^ { NSLog(@"tick !!!!!!!!!!!!"); if ( mySelf == nil ) NSLog(@"I no longer exist - WTF!"); [mySelf _teste]; }); }
你可以清楚地看到,一旦“红色”vc被解雇,确实,股票代码停止运行:“红色”已经消失.
它似乎工作可靠.你的输出会看起来像这样…
2014-10-22 17:26:36.498 [1738:111092] tick --- !!!!!!!!!!!! 2014-10-22 17:26:37.031 [1738:111092] tick --- !!!!!!!!!!!! 2014-10-22 17:26:37.576 [1738:111092] tick --- !!!!!!!!!!!! 2014-10-22 17:26:38.124 [1738:111092] tick --- !!!!!!!!!!!! 2014-10-22 17:26:38.674 [1738:111092] tick --- !!!!!!!!!!!! 2014-10-22 17:26:39.217 [1738:111092] tick --- !!!!!!!!!!!! 2014-10-22 17:26:39.764 [1738:111092] tick --- !!!!!!!!!!!! 2014-10-22 17:26:39.764 [1738:111092] I no longer exist --- WTF!
要重申,如AnujYadav指出,如果您在父VC中使用属性为“红色”…
@property (strong) Red *red;
然后
self.red = (Red *)[self.storyboard instantiateViewControllerWithIdentifier:@"RedID"];
确实这不行.在这种情况下,您必须在父母中self.red = nil,否则不会消失.