- objective-c - iOS 5 : Can you override UIAppearance customisations in specific classes?
- iphone - 如何将 CGFontRef 转换为 UIFont?
- ios - 以编程方式关闭标记的信息窗口 google maps iOS
- ios - Xcode 5 - 尝试验证存档时出现 "No application records were found"
我创建了一个 NSOperation 子类来处理一些 zip 存档操作。无论如何,如果我重写 -start
或 -main
这段代码总是会发生:
if ([NSThread isMainThread]) {
NSLog(@"I am in the main thread");
return;
}
知道发生了什么吗?
我试过添加这个 block :
- (void) start { //also tried overriding main
if ([NSThread isMainThread]) {
NSLog(@"In main thread, trying again");
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self start];
});
return;
//hard working code etc...
//cpu intensive zip operations...
}
但这会导致崩溃,EXC_BAD_ACCESS
违规指向 dispatch_async
行。
最佳答案
No matter what, if I override -start or -main this block of code always happens:
主操作队列在主线程上运行。来自 +[NSOperationQueue mainQueue]
的文档:
The returned queue executes operations on the main thread. The main thread’s run loop controls the execution times of these operations.
因此,在另一个线程中运行是将操作添加到哪个队列的问题,而不是如何编写操作代码的问题。如果您希望您的操作在不同的操作队列上运行,您需要使用以下方法创建您自己的队列
NSOperationQueue* aQueue = [[NSOperationQueue alloc] init];
您可以在 Adding Operations to an Operation Queue 中找到示例在并发编程指南中。
But this causes a crash, an EXC_BAD_ACCESS violation pointing at the dispatch_async line.
听起来 -[NSOperation start]
可能不是可重入的。您的代码有效地在两个不同的线程上执行相同的方法。其实看看the docs for -start
,很明显您的代码将无法运行:
You can call this method explicitly if you want to execute your operations manually. However, it is a programmer error to call this method on an operation object that is already in an operation queue or to queue the operation after calling this method. Once you add an operation object to a queue, the queue assumes all responsibility for it. [Emphasis added. -Caleb]
换句话说,不要那样做。
关于ios - NSOperation 没有在后台线程中发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18049727/
我是一名优秀的程序员,十分优秀!