【问题标题】:Recommended thread layer to use for iPhone development?推荐用于 iPhone 开发的线程层?
【发布时间】:2009-08-11 17:04:48
【问题描述】:
我是 Objective C 和 Mac 开发的新手...看来我可以在我的应用程序中使用 Posix 线程 API。这是推荐的方式吗?还是我应该将它们的某些 Apple API 用于互斥锁、条件变量和线程?
我应该补充一点,我正在为 iPhone 开发。
我想准确地添加我正在尝试做的事情。基本上,CoreLocation 是异步的……你告诉它开始更新你,然后它只是定期调用你的更新方法……
我遇到的问题是我需要另一个线程来阻塞,直到发生更新...如何使主应用程序线程阻塞,直到发生至少一个 CoreLocation 更新?他们是 NSConditionVariable 吗? :)
【问题讨论】:
标签:
iphone
variables
multithreading
conditional-statements
【解决方案1】:
我建议一种更简单的陷入线程的方法是使用以下调用:
[self performSelectorInBackground:(@selector(myMethod)) withObject:nil];
这将自动创建一个新的后台线程供您运行。顺便确保您在后台方法中执行以下操作:
-(void) myMethod {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// code you want to run in background thread;
[pool drain];
}
这是必要的,因为除了主线程之外,没有为任何线程设置默认的自动释放池。
最后,谈到阻塞主线程,您可以使用后台线程中的以下内容来执行此操作:
[self performSelectorOnMainThread:(@selector(myOtherMethod)) withObject:nil waitUntilDone:YES];
可选的第三个参数将为您保留主线程,如果您希望它这样做。
希望有帮助!
【解决方案3】:
我建议不要通过挂起来阻止用户界面,而是在您收到第一次更新之前显示某种加载屏幕。可能看起来像这样:
- (void)viewDidLoad {
...
[myCLLocationManager beginUpdates];
[self showLoadingIndicator];
....
}
- (void)locationManager:(CLLocationManager *)manager didReceiveUpdates {
[self hideLoadingIndicator];
// Additionally load the rest of your UI here, if you haven't already
}
不要逐字引用这些方法调用,但这就是我建议从本质上解决您的问题的方式。
【解决方案4】:
是的,有一个 NSCondition 对象,它可能会为您提到的 CoreLocation 场景做您想要的。