一、Block循环引用
防止block循环引用的方法:(弱引用)
__weaktypeof(self) weakself = self;
self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
__strongtypeof(self) strongself = weakself;
strongself.page = 1;
[strongself.dataArr removeAllObjects];
[strongself loadData];
}];
二、delegate循环引用问题:
delegate循环引用问题比较基础,只需注意将代理属性改为weak即可
@property(nonatomic,weak) id delegate;
三、NSTimer循环引用
例如下面的例子,定时器并不能最终销毁:
#import "TestNSTimer.h"
@interface TestNSTimer ()
@property (nonatomic, strong) NSTimer *timer;
@end
@implementation TestNSTimer
- (instancetype)init {
if(self = [superinit]) {
_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeRefresh:) userInfo:nil repeats:YES];
}
returnself;
}
- (void)timeRefresh:(NSTimer*)timer {
NSLog(@"TimeRefresh...");
}
- (void)cleanTimer {
[_timer invalidate];
_timer = nil;
}
- (void)dealloc {
[superdealloc];
NSLog(@"销毁");
[self cleanTimer];
}
在外部调用时:
TestNSTimer *timer = [[TestNSTimer alloc]init];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[timer release];
});
应改为:
TestNSTimer *timer = [[TestNSTimer alloc]init];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[timer cleanTimer];
[timer release];
});
需要注意cleanTimer的调用时机从而避免内存无法释放
网友评论