循环引用

1.block循环引用引起内存泄露。

循环引用指两个对象相互强引用了对方,即retain了对方,从而导致谁也释放不了谁的内存泄露问题。如声明一个delegate时一般用assign而不能用retain或strong,因为你一旦那么做了,很大可能引起循环引用。因为block在拷贝到堆上的时候,会retain其引用的外部变量,那么如果block中如果引用了他的宿主对象,那很有可能引起循环引用。

__weak typeof(self) weakSelf = self;

一个对象中的block块中的访问自己的属性也会造成循环引用。解释:http://blog.csdn.net/fengsh998/article/details/38090205

    - (IBAction)onTest:(id)sender  {    

      BlockDemo *demo = [[BlockDemo alloc]init];  

        __weak typeof(BlockDemo) *weakDemo = demo;  

      [demo setExecuteFinished:^{  

            if (weakDemo.resultCode == 200) {  

            NSLog(@"call back ok.");

          }  

       }];

       [demo executeTest];  

    }  

2. NSTime

@interface FtKeepAlive : NSObject
{
    NSTimer*              _keepAliveTimer; // 发送心跳timer
}
//实现文件
_keepAliveTimer = [NSTimer scheduledTimerWithTimeInterval:_expired target:self selector:@selector(keepLiveStart) userInfo:nil repeats:YES];
类持有了_keepAliveTimer,_keepAliveTimer又持有了self,造成循环引用。
NSTimer会持有对象,所以:在删除对象之前,需要将timer的invalidate方法。
-(void)stopKeepAlive{
    [_keepAliveTimer invalidate];
    _keepAliveTimer = nil;
}

3.代理  要用assign声明。

转载于:https://www.cnblogs.com/xing-li/p/4503608.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值