OC项目出现循环引用/强引用的解决方法
iOS开发dealloc方法不调用的原因
快下班的时候测试告诉我,你的这个提示弹框怎么总是叠加重复弹出?发出了灵魂拷问,让我也是心里一紧,只能加个班了……
经过排查是通知(NSNotificationCenter)
被重复监听导致的,只能说明一个问题注册的通知监听没有及时销毁,只能是- (void)dealloc
方法未被调用
dealloc
不调用一般有以下三个原因:
① 使用
NSTimer
计时器没有invalidate
掉,这里要注意,先[_timer invalidate]
;然后再_timer = nil
;就OK了;
② 有循环引用强引用的地方造成的(block中出现循环引用);
③ 使用了delegate没有取消或者是未使用weak/assign
修饰
经排查是因为多人开发的项目导致的block
中出现循环引用
引起的,一般使用__weak typeof(self) weakSelf = self
可以使用以下的宏定义更方便的去解决block
的循环引用问题
#define kWeakSelf(type)__weak typeof(type)weak##type = type;
#define kWS(weakSelf) __weak __typeof(&*self)weakSelf = self;
#define kStrongSelf(type)__strong typeof(type)type = weak##type;
也可以使用:
@weakify();
@strongify();
同样也要避免出现强引用问题,合理使用属性修饰符:
关键字 | ARC或MRC | 修饰对象说明 |
---|---|---|
atomic | both | 原子,线程安全,效率低,多线程操作时才使用 |
nonatomic | both | 非原子,线程不安全,效率高,经常使用 |
retain | mrc | 修饰对象 ,强引用 |
strong | arc | 修饰对象,强引用 |
weak | arc | 修饰代理delegate,修饰对象弱引用 |
assign | both | 修饰基本数据类型(int,float,boolean) |
copy | both | 修饰字符串,block等 |
常见的修饰词使用举例:
@property (assign, nonatomic) NSInteger status;
@property (assign, nonatomic) BOOL isSelected;
@property (copy, nonatomic) NSString *city;
@property (strong, nonatomic) NSArray *bannerAdDataArr;
@property (copy, nonatomic) void (^UMSHARE_RESULT_BLOCK)(id resultData,UMSocialPlatformType platformType,NSError * error);
@property (weak, nonatomic) id <LRSSheetCityPickerDelegate> delegate;
网友评论