1. 解析
//每5秒刷新一次
- (void)method1{
self.timer = [NSTimer scheduledTimerWithTimeInterval:5] target:self selector:@selector(update) userInfo:nil repeats:YES];
}
- (void)dealloc{
[self.timer invalidate];//釋放定時器
}
這個對象持有計數器,用時計數器也持有了對象,這就導致了循環引用。
如果一旦有了循環引用,那么dealloc方法永遠不會被調用,計數器也不會被執行。僅僅將self.timer=nil,是不能解決的
2. 解決方案
2.1 主動調用invalidate。
1、在視圖控制器中,在視圖控制器當從一個視圖控制容器中添加或者移除viewController后,該方法被調didMoveToParentViewController。
- (void)didMoveToParentViewController:(UIViewController *)parent{
[self.timer invalidate];
}
2、 通過監聽控制器返回按鈕
-(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 將調用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{
//在此得到最新的數組模型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
}
//此處的對象沒有被其他對象持有,直接調用dealloc
- (void)dealloc{
[ self.chtool clearTimer]
}
@end