iOS Development Help

Associate
Joined
25 Feb 2007
Posts
905
Location
Midlands
Hi,

Can any iOS devs help me with this?

I'm downloading and parsing a JSON feed on a button press. This button also loads the next view (via a storyboard segue)

I'm getting an error about a thread other than the main one trying to update the UI - I'm assuming that this is because I'm using a secondary thread to download and parse the file and then the UI change also occurs in the secondary thread.

How can I force the UI change to occur in the main thread? The button has to control both actions (downloading/parsing the file and the UI change) as a parameter for the JSON download is created using a text box value on the same view.

Thanks!
 
Are you using Grand Central Dispatch or NSThread?

if using GCD
To get back to the main queue

you need to do:

dispatch_async(dispatch_get_main_queue(), ^{ // update UI here});

EDIT* for iOS apps its best to start using GCD, its the way apple want you to do it.

http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/ThreadMigration/ThreadMigration.html

GCD is actually C and not objective-c so it will look a little different.

but this is how you use it.


To create a new queue:
dispatch_queue_t queue;
queue = dispatch_queue_create("com.reverseDNS.Notation", NULL);

to jump to that queue:

dispatch_async(queue, ^{
// this is called a block - this ^ means block
//add your code here
});

to get back to your main queue (All UI elements must be updated on the main queue, else apple will probably reject you app)

dispatch_async(dispatch_get_main_queue(), ^{

// update UI here

});

You want to be careful though because when you connect to your JSON object/method to pull out the data... You don't actually know how long that's going to take because your relying on another server.

and if you jump back to your main queue before you've connected your never going to display your data.

It can be a bit of a pain, its a lot of messing around.

but call your JSON object /method in a new queue, but inside the class/method switch back to your main queue... It sounds abit pointless, but ive shaved off a lot of seconds from pulling JSON data from a webservice by doing that.

Just switching back and forth from queues seems to eliminate 'queue lag'
 
Last edited:
Hi mate,

Sorry it's taken me a while to come back to you on this!

I've tried to implement what you've suggested, but it doesn't seem to have made any difference.

I think it's because I don't actually change the view in the code anywhere - I've got the code under where I've created a new queue to pull through my JSON data, but then I don't have anything to put under the get_main_queue part as all of the view switching is done in the Storyboard?

Do I need to add code to change the view, or should I leave it with the storyboard to sort out, and fix this some other way?
 
Back
Top Bottom