我有一个iPhone
应用程序,其中我想在后台执行一个方法,每个1
秒。iPhone SDK - 在后台线程中运行重复过程
所以在我的主线程,我在我的UIViewController
viewDidLoad()
有以下代码:
[NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(repeatedMethod) userInfo:nil repeats:YES];
以下方法:
-(void)repeatedMethod {
if(!processIsRunning) {
processIsRunning = YES;
[self performSelectorInBackground:@selector(runProcessInBackground:) withObject:myImage];
}
}
-(void)runProcessInBackground:(UIImage *)image {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
... Some operations ...
... also call a method on the main thread which sets isProcessRunning to NO
[pool release]
}
的方式,我有这样的设置,一个新的线程每秒产生一次(除非该进程仍在运行,这要归功于我的processIsRunning
标志)。
现在,我的问题是:
(1)这是做到这一点的最好方法是什么?还是有更合适的方式来保留和重用后台线程?
(2)什么可能是最快的方法来做到这一点?每次调用该方法时,我是否都会花时间旋转新的后台线程?
代码可以正常工作,当我在主线程上运行所有内容(我最终不想这么做)时,它会稍微慢一些。
任何建议将是伟大的! 有没有人处理过这类问题?
非常感谢, 布雷特
看看我对这个问题的回答:http://stackoverflow.com/questions/8759264/worker-thread-ios/8759329#8759329 – 2012-03-30 19:27:43
@安德鲁,谢谢!但有一个问题:我怎么能通过一个对象来看待GCD?在我上面的代码中,这个对象是'myImage'。 – Brett 2012-03-30 19:33:53