我需要创建一个例程,在一个恒定的时间段内自动保存文件内容,即执行保存指令的背景循环。我认为使用了performSelector的递归调用,如下所示:
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self performSelector:@selector(saveMethod) withObject:nil afterDelay:kTimeConstant];
}
- (void)saveMethod{
//The save logic should to be here
[self performSelector:@selector(saveMethod) withObject:nil afterDelay:kTimeConstant];
}
它可以工作,但是当我离开viewController时,它仍在运行,它必须停止。 有没有更好的方法来执行它?谢谢!
答案 0 :(得分:2)
有一个函数NSRunLoop cancelPreviousPerformRequestsWithTarget:selector:object:
,允许您取消performSelector调用。卸载视图控制器时调用此方法
即
[NSRunLoop cancelPreviousPerformRequestsWithTarget:self selector:@selector(saveMethod) object:nil];
答案 1 :(得分:2)
这可能是一个更好的实现:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// Start timer and sets it to a property called saveTimer
self.saveTimer = [NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(saveMethod:)
userInfo:nil
repeats:YES];
}
- (void)saveMethod:(NSTimer*)theTimer {
// The save logic should to be here
// No recursion
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
// Stop timer
[self.saveTimer invalidate];
}
这是在主线程上运行的,所以它可能不是最好的实现,但它应该比你现有的更好。