This post originated from an RSS feed registered with Agile Buzz
by Keith Ray.
Original Post: Asych it, or Multi-thread it
Feed Title: MemoRanda
Feed URL: http://homepage.mac.com/1/homepage404ErrorPage.html
Feed Description: Keith Ray's notes to be remembered on agile software development, project management, oo programming, and other topics.
Usually, if you can't make it faster, you keep the UI responsive by putting the work in the background. In a Cocoa application, sometimes you don't even need a separate thread. In one application that I was working on, I noticed that a particular function call was taking a few seconds to complete, and because I was calling it when I was handling the processing of a string received from the UI, the last character wasn't being shown in the UI. You type "abcd", see "abc" on the screen, and then two seconds later see "d". So I deferred the call using an NSObject method:
[self performSelectorOnMainThread: @selector(myLengthyMethod) withObject: nil waitUntilDone: NO ];
This allows the UI to show the last character, and for me to start spinning the "waiting" indicator, without going to the trouble of creating another thread. This was a modal situation - the user can't proceed until the function call returns. In a non-modal situation, you might want to use a secondary thread, perhaps with a call like this: