1

我需要创建一个在恒定时间段内自动保存文件内容的例程,即执行保存指令的背景循环。我认为在使用 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 时,它仍在运行,并且必须停止。有没有更好的方法来执行它?谢谢!

4

2 回答 2

2

有一个函数NSRunLoop cancelPreviousPerformRequestsWithTarget:selector:object:允许您取消 performSelector 调用。卸载视图控制器时调用它

IE。

 [NSRunLoop cancelPreviousPerformRequestsWithTarget:self selector:@selector(saveMethod) object:nil];
于 2013-06-27T17:04:24.413 回答
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];
}

这是在主线程上运行的,所以它可能不是最好的实现,但它应该比你目前拥有的更好。

于 2013-06-27T17:17:28.957 回答