Adding a ViewControllers's view as subView

别说谁变了你拦得住时间么 提交于 2019-12-14 01:53:43

问题


I am adding a ViewControllers view as a subView to another ViewController,

Example :

In FirstScreen viewcontroller i do this,

         [self.view addSubview:self.secondScreen.view]; 

And Once i remove it from FirstScreen i do this

         [self.secondScreen.view removeFromSuperView];
          self.secondScreen=nil;  

But While Adding the subView ViewDidLoad method is called but while removeFromSuperView ViewDidUnLoad is not called.

My Question

1) will all my objects in my secondScreen will get deallocated once i set the instance self.secondScreen to nil

2)Is it safe to do like this so that i wont get any leaks or memory warning


回答1:


Assuming that your app supports from iOS 5.0 onwards, you need to add it as,

[self addChildViewController:self.secondScreen];
[self.view addSubview:self.secondScreen.view]; 

Similarly for removing you can use removeFromParentViewController and then remove from superview. Check apple documentation here.

ViewDidUnLoad is deprecated from iOS 6.0 onwards and will not get called. Check the documentation here.

Regarding your questions,

1) will all my objects in my secondScreen will get deallocated once i set the instance self.secondScreen to nil

Once you are done with self.secondScreen class, it will start releasing objects inside this class once you set it to nil. If you are using ARC, you dont have to worry much about releasing. OS will take care of those things.

2)Is it safe to do like this so that i wont get any leaks or memory warning

Yes, this is fine if you are using ARC. For non-ARC, you need to make sure that you have released all variables properly in this class. Make sure the retain/release are all balanced in that case.




回答2:


ViewDidUnload isn't called when a view is removed from a ViewController, it is called when the view is unloaded from memory. The iOS documentation about this has the following caveat:

Called when the controller’s view is released from memory. (Deprecated in iOS 6.0. Views are no longer purged under low-memory conditions and so this method is never called.)

Note the "deprecated" and the fact that "this method is never called".



来源:https://stackoverflow.com/questions/13797035/adding-a-viewcontrollerss-view-as-subview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!