2012-01-25 31 views
1

我需要每10分钟左右调度一次后台操作。该操作包括从核心数据中收集对象并将其信息上传到Web服务,而不是以任何方式更改它们。使用NSTimer在ios中启动NSThread

我想到的方法是在每10分钟触发的应用程序委托中创建一个nstimer。这将触发NSThread,它将在后台运行操作,不会对用户造成任何干扰。正常退出后,线程将在此处运行。

我一直在寻找开始一个线程,并在每次执行操作后将其设置为睡眠,但计时器方法似乎是最干净的。

网络上的其他建议是使用runloops,但我不能看到在这种特定情况下使用。

是否有人有建议或想告诉他们如何解决类似的情况。

问候

回答

2

定时器听起来像实际启动你的线程正确的方法。要设置了只是把这个在您的应用程序代理

[NSSTimer scheduledTimerWithTimeInterval:60.0 * 10.0 target:self selector:@selector(startBackgroundMethod) userInfo:nil repeats:YES]; 

然后创建你这样的背景方法代码:

- (void)startBackgroundMethod 
{ 
    //the timer calls this method runs on the main thread, so don't do any 
    //significant work here. the call below kicks off the actual background thread 
    [self performSelectorInBackground:@selector(backgroundMethod) withObject:nil]; 
} 

- (void)backgroundMethod 
{ 
    @autoreleasepool 
    { 
     //this runs in a background thread, be careful not to do any UI updates 
     //or interact with any methods that run on the main thread 
     //without wrapping them with performSelectorOnMainThread: 
    } 
} 

至于是否实际上必要做这项工作在后台线程,即取决于它是什么。除非严格要求,否则应该避免使用线程,因为可能存在并发错误,所以如果您告诉我们线程要做什么,我们可以建议基于runloop的方法是否更合适。

+0

嗨,尼克,谢谢你的回答。基本上线程拥有共享上下文并从持久存储中检索对象。然后它从对象获取信息并将其上传到Web服务。它不会以任何方式改变对象。这是因为我正在考虑这种方法的时间安排和上传。我正在使用ASIHTTPRequest上传到web服务。 – Bjarke

+0

您可能想重新考虑使用ASI,因为开发人员已经正式放弃了它,并且它不适用于ARC。您可以使用常规的异步NSURLConnection完成上载,并且可以在runloop上运行而不会阻塞UI,也不需要从新线程中产生(我假设它在内部使用线程,但您不需要自己管理并发)。 –