Tuesday, March 23, 2010

iPhone Sequential Execution

Something that I've found a little odd in iPhone code is that things don't always execute sequentially. Actually, I'm sure they do, but because they all seem to load at once they don't seem like it. I found a great method of something executing right away. By encapsulating a method in the following function, things before it run, and then this executes and runs. This is especially useful to be so that I can have an activity indicator (spinning ball) run while this happens in the background.

// Start up our activity indicator while we collect the data

[self startActivityIndicator];

// Run the loadData method right now

[self performSelector:@selector(loadDataInBackground) withObject:nil afterDelay:0.0];

I can then end the Activity Indicator when I get to the end of the "loadDataInBackground" method. If we just call both of the methods, the ActivityIndicator doesn't display until just as the loadData method ends.


1 comment:

Shayne O said...

Ah, I can explain this. Most of your code in an iphone app runs on a single thread, as does the UI, and this is generally done via a sort of cooperative model where you do some code, and then release control back to the OS which then updates stuff on the main UI. The problem is, things like web service calls can take a long time to return control, meaning that things like activityindicators cant display until *after* the network command. What the perform selector stuff does is to run your code on another thread leaving the first thread free to update UI.

Theres a catch though, you need to be aware that you can get crashes and corruption writing to the UI and certain other structures from outside the main thread unless you either re-join the main thread or implement some sort of locking mechanism and pay close attention to atomicity. Best just to rejoin the main thread once the networking or whatever has completed.