I have an app which uses a UISearchBar to dynamically search from an external API based on user input.
The app is searching the external API fine and displaying results correctly, but when I select any row from the search results, the screen freezes and I am getting this error;
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
I have absolutely no idea how I can fix this.
Here is the code;
- (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];
}
The fix is conceptually simple; don’t update the UI from your thread.
Assuming the
parseDidCompleteis where the message is sourced, then something like this will “work”:“Work” because threading is hard and this answer completely ignores any synchronization issues you might have.
Note that you’d be better off using
NSOperationandNSOperationQueue. They are well documented and there are a bunch of examples.