循环引用

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声明。

posted @ 2015-05-14 16:10  轻风&星  阅读(227)  评论(0编辑  收藏  举报