笔者在阅读中总结了一下,在iOS平台容易引起循环引用的几个场景:
一、parent-child相互持有、委托模式
二、block
三、NSTimer
四,比如把self假如array中。也会造成循环引用
五,使用类别添加属性
一、parent-child相互持有、委托模式
【案例】:
@interface FTAppCenterMainViewController ()
{
}
@property(weak,nonatomic) UITableView* myTableView;
@end
这里面的myTableView就使用了weak修饰符。
@property (nonatomic, weak) id<FTActionSheetDelegate>delegate;
【推荐方法】:
child只有parent的对象为weak类型:
@property (nonatomic, weak) id<FTActionSheetDelegate>delegate;
二、block
【案例】:
看下面的代码:
typedef void (^RequestNaviCallBack)(NSInteger naviCode,NSInteger httpCode,NSError * error);
@interface FtNaviManager : NSObject
{
}
@property (nonatomic, strong) RequestNaviCallBack naviCallBack;
这是一个请求导航的类,类属性持有了RequestNaviCallBack,这时,如果RequestNaviCallBack再持有self,
必然造成循环引用。
当然还有一些隐式(间接)循环引用。ObjectA 持有ObjectB,ObjectB持有block。那么在block中调用ObjectA的self会造成间接循环引用。
【推荐方法】:
如果有显示循环引用,编译器会提示警告,在block引用self的时候最好使用weak-strong dance技术。
详细的weak-stong-dance技术,查看这里
三、NSTimer
【案例】:
@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;
}
四,比如把self加入array中。也会造成循环引用
五,使用类别添加属性
比如:有一个类A,给A动态添加属性p。如果p中再引用类A,容易造成循环引用