关于removeFromSuperview和addSubview

-(void)removeFromSuperview 官方API说明:

Unlinks the receiver from its superview and its window, and removes it from the responder chain.

- Discussion:

If the receiver’s superview is not nil, the superview releases the receiver. If you plan to reuse a view, be sure to retain it before calling this method and release it again later as appropriate.

- important:

Never call this method from inside your view’s drawRect: method.

译:把当前view从它的父view和窗口中移除,同时也把它从响应事件操作的响应者链中移除。

如果当前view对象的父视图不为空,则父视图会release一次当前视图对象。如果你还想重用当前view,你应该在调用removeFromSuperview之前,retain一次当前view对象,但不要忘记,在恰当的时候要release它,以确保没有内存泄露。

永远不要在你的view的drawRect方法中调用removeFromSuperview;

从官方 API 中可以看出一个view的操作关系到两个方面,视图结构和响应者链, 当调用此方法时,当前 view 并其 subviews 一同移除视图及事件响应。

一般情况下在 ARC 中不需要将其指针置为 nil, 因为这些都是系统在管理,当前控制器 dealloc 时,系统自动回收。但很多时候,viewcontroller的实例变量调用此方法后,还会将该实例变量置为 nil。如以下情况

//第1种

if(firstTableView !=nil) {    

[_firstTableView removeFromSuperview];

}

//第2种if(firstTableView !=nil) {    

[_firstTableView removeFromSuperview];       

_firstTableView =nil; 

}

-(void)refreshForView{

if(_firstTableView ==nil) {      

[selfconfigureFirstTableView];   

}

}

当执行 refreshForView 方法来重新添加该控件时,就可以看出明显区别了,第2种情况下,重新添加该控件判断时,_firstTableView肯定为 nil, 所以会进行再次创建。第1种, 虽然_firstTableView 已经从页面上移除了, 但其指针还并不为 nil, 因为当前控制器还没有回收这些指针,故在重新添加该控件判断时,_firstTableVieW 并不会重新创建,造成该控件丢失显示的问题.

总结,在实际开发过程中,遇到 removeFromSuperview 的时候,在需要拿当前指针来进行判断的情况下,移除后需要将指针置为 nil. 不需要进行判断的情况下, 系统会自动管理好这些指针.

-(void)addSubview 官方API说明:

Adds a view to the end of the receiver’s list of subviews.

- Discussion:

This method establishes a strong reference to view and sets its next responder to the receiver, which is its new superview.

Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.

添加视图至当前视图的子视图中的最顶层

这个方法建立一个强引用至要添加的视图,并设置他的下一响应者到他的父视图.

视图只可以拥有一个父视图.如果视图已经有一个父视图,之前的父视图不再是接受者.这个方法在添加到新的父视图之前会先从旧父视图上移除.

所以当执行 addSubview 方法时, 因为父视图对 viwe 的强引用, 故view 会增加一次引用计数。同样的,执行 removeFromSuperview 方法时, view 会 release 一次。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 译:把当前view从它的父view和窗口中移除,同时也把它从响应时间操作的响应者链中移除。如果当前view对象的父...
    小笨憨阅读 939评论 0 3
  • /* UIViewController is a generic controller base class th...
    DanDanC阅读 2,054评论 0 2
  • ViewsBecause view objects are the main way your applicati...
    梁光飞阅读 772评论 0 0
  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 2,081评论 0 9
  • 今天冷飕飕的,天也阴的厉害,总有种要下雪的感觉。 中午的时候幼儿园通知,今天晚6点开家长会,临近放学把我好忙一顿,...
    SummerSL阅读 217评论 0 0

友情链接更多精彩内容