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
网友评论