前言
-
调用时机
- 苹果官方文档
A class may provide a method definition for an instance method named
dealloc. This method will be called after the final release of the
object but before it is deallocated or any of its instance variables
are destroyed.
The superclass’s implementation of dealloc will be called automatically
when the method returns.
翻译:
dealloc方法在最后一次release后被调用,但此时实例变量(Ivars)并未释放,父类的dealloc的方法将在子类dealloc方法返回后自动调用,也就是说对象被销毁后会调用dealloc方法
使用场景
-
重写这个方法可以处理除了对象的实例变量之外的其他资源
-
释放定时器
-
移除通知
-
移除代理 备注:***ARC下不能调用父类的dealloc方法 ***
- (void)dealloc { [self.timer invalidate] [[NSNotificationCenter defaultCenter]removeObserver:self]; }
原因汇总
-
block的循环引用问题(90%的比例)
-
block里面使用了self.name或者_name
self.table.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
self.name = @"强引用属性";
}];
//解决方案
__weak typeof(self) weakSelf = self;
self.table.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
weakSelf.name = @"强引用属性";
}]; -
block里强引用了全局变量
@implementation SomeViewControllefr
{
NSInteger page;
}
self.table.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
page+=1;//这里模仿分页加载场景
}];// 解决 把全局变量声明成属性 @property (nonatomic,assign) NSInteger currentPage;
-
-
强引用代理
@property (nonatomic, strong) id<SomeDelegate> delegate;
-
NSTimer
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(someMethod) userInfo:nil repeats:YES]; [self.timer setFireDate:[NSDate dateNow]]; //解决 if (self.timer && [self.timer isValid]) { [self.timer invalidate]; self.timer = nil; // 不置为nil也行 };
后续
-
欢迎拍砖灌水,大家一起来讨论不足。
-
转载请注明出处:http://www.jianshu.com/p/2854b5b6bbf8
-
喜欢的看官给个红心
-
推荐深度阅读 OC源码 —— alloc, init, newdealloc http://www.jianshu.com/p/44f2ef4552a8
网友评论