objective-c - 错误消息,不应从辅助线程调用UIKit

标签 objective-c multithreading cocoa-touch uikit

我有一个应用程序,它使用UISearchBar根据用户输入从外部API动态搜索。

该应用程序可以很好地搜索外部API并正确显示结果,但是当我从搜索结果中选择任何行时,屏幕将冻结,并且出现此错误;

Tried to obtain the web lock from a thread other than the main thread or the web thread UIKit should not be called from a secondary thread



我完全不知道如何解决此问题。

这是代码;
- (void) run: (id) param  {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL: [self URL]];
    [parser setDelegate: self];
    [parser parse];
    [parser release];
    [delegate parseDidComplete];
    [pool release];
} 

- (void) parseXMLFile: (NSURL *) url
{ 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    [self setURL: url];
    NSThread* myThread = [[NSThread alloc] initWithTarget:self
                                                 selector:@selector(run
   object: nil];
    [myThread start];
    [pool release];
}

最佳答案

"Tried to obtain the web lock from a thread other than the main thread or the web thread UIKit should not be called from a secondary thread"



该修复在概念上很简单;不要从您的线程更新UI。

假设parseDidComplete是消息的来源,那么类似的事情将“起作用”:
[delegate performSelectorOnMainThread: @selector(parseDidComplete) withObject: nil waitUntilDone: YES];

“工作”是因为线程很难,并且此答案完全忽略了您可能遇到的任何同步问题。

请注意,最好使用NSOperationNSOperationQueue。它们有据可查,并且有很多示例。

关于objective-c - 错误消息,不应从辅助线程调用UIKit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4672254/

相关文章:

iphone - 状态栏与带有 xcode5 的 iOS 7 中的应用程序 View 重叠

iphone - Objective-C 中的位转换工具

c++ - std::lock() 相当于 boost::shared_mutex?

ios - 处理 openURL : with Facebook and Google

ios - UIWebView 无法选择文本

objective-c - 在 xcode 中搜索硬编码文本

java - CPU 使用率高,几乎所有线程都处于阻塞状态

Python 3 - 托管服务器

iphone - Storyboard中的自定义字体?

iphone - TableView 不会加载到 UINavigationController 内部