如何在objective-c中创建后台循环例程的更好方法?

时间:2013-06-27 16:58:20

标签: ios objective-c nsthread performselector

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

2 个答案:

答案 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];
}

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