1. 解析
//每5秒刷新一次
- (void)method1{
self.timer = [NSTimer scheduledTimerWithTimeInterval:5] target:self selector:@selector(update) userInfo:nil repeats:YES];
}
- (void)dealloc{
[self.timer invalidate];//釋放定時器
}
這個對象持有計數(shù)器,用時計數(shù)器也持有了對象臀晃,這就導(dǎo)致了循環(huán)引用觉渴。
如果一旦有了循環(huán)引用,那么dealloc方法永遠(yuǎn)不會被調(diào)用徽惋,計數(shù)器也不會被執(zhí)行案淋。僅僅將self.timer=nil,是不能解決的
2. 解決方案
2.1 主動調(diào)用invalidate险绘。
1踢京、在視圖控制器中,在視圖控制器當(dāng)從一個視圖控制容器中添加或者移除viewController后宦棺,該方法被調(diào)didMoveToParentViewController漱挚。
- (void)didMoveToParentViewController:(UIViewController *)parent{
[self.timer invalidate];
}
2、 通過監(jiān)聽控制器返回按鈕
-(id)init{
self = [super inti];
if(self){
self.navigationItem.backBarButtonItem.target = self;
self.navigationItem.backBarButtonItem.action = @selector(backView);
}
}
- (void)backView{
[self.timer invalidate];
self.navigationColltroller popViewContrllerAnimated:YES];
}
2.2 將調(diào)用invalidate的方法放到其他類中.
講計時器功能從CHViewController中分離
定義一個CHTimerTool計時器工具類
@implemention CHTimerTool
-(void)initWithTimer:(NSTimeInterval)interval target:(id)target selector:(SEL)selector{
self= [super inti];
if(self){
self.target = target;
self.timer = [NSTimer scheduledTimerWithTimeInterval:5] target:self selector:@selector(update) userInfo:nil repeats:YES];
}
}
- (void)update{
//在此得到最新的數(shù)組模型modelList
if([target respodnsToSelector:selector])
{
[target performSelector:selector withObject:modelList];
}
}
- (void)clearTimer{
[self.timer invalidate];
}
@end
@interface
@property (nonatomic, retain)CHTimerTool *chtool;
@end
@implemention CHViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.chtool = [CHTimerTool initWithTimer:30 target:self selector:@selector:(updateUI:)];
}
- (void)updateUI:(NSArray*)modelList{
//更新UI
}
//此處的對象沒有被其他對象持有渺氧,直接調(diào)用dealloc
- (void)dealloc{
[ self.chtool clearTimer]
}
@end