2013-06-27 14 views
1

我需要创建一个例程自动保存文件内容在一定时间,即执行保存指令的backgroung循环。我在使用鑫卡特performSelector的递归调用象下面这样:如何在objective-c中创建后台循环例程?

- (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的,它仍在运行,并且它必须停下来。 有没有更好的方法来执行它?谢谢!

+1

你已经张贴在背景没有做任何事情(即在一个单独的线程)的代码。你真的想要保存在非主线程上发生吗? –

+1

如果您不希望它被执行,那么您可以在'viewWillDissapear:'方法中取消@selector方法。这不是后台方法。它会在延迟后在主线程中调用。 – TheTiger

+0

我有一个使用RichTextEditor,我想实现一个自动保存在一个时间段保存HTML内容,但它不'吨可以锁定的执行,是用户看不到的,所以我认为它should't运行主线程。 –

回答

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

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

+0

它对我来说很有意思。谢谢你Firo! –

+0

我不会说它更好的实现。 – TheTiger

+0

它确实工作得很好,但invalidade简化版,被停止计时器=( –

2

有一个功能NSRunLoop cancelPreviousPerformRequestsWithTarget:selector:object:,它允许您取消performSelector电话。当你卸载视图控制器

即调用此。

[NSRunLoop cancelPreviousPerformRequestsWithTarget:self selector:@selector(saveMethod) object:nil];