update ui elements from a background thread in ios
Thu, Apr 11, 2013
This is a weird one, yet not weird at all really. I was playing around with Grand Central Dispatch (GCD) in viewDidLoad:
dispatch_queue_t queue = dispatch_queue_create("com.codebrane.onlineTimeQueue", NULL);
dispatch_async(queue, ^{
… some code to retrieve the time from an online service
self.textField.text = responseAsText;
});
It worked fine when textField was a label but when I changed to use a textField to get the full response displayed, it produced this error:
Tried to obtain the web lock from a thread other than the main thread or the web thread.
This may be a result of calling to UIKit from a secondary thread.
Crashing now..
Silly me, I should have remembered you should update UI elements from the main thread:
dispatch_queue_t queue = dispatch_queue_create("com.codebrane.onlineTimeQueue", NULL);
dispatch_async(queue, ^{
… some code to retrieve the time from an online service
dispatch_async(dispatch_get_main_queue(), ^{
self.textField.text = responseAsText;
});
});