关于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) {
        [self configureFirstTableView];
    }
}

当执行 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 一次。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值