iHarder.net

ThreadWorker

Support This Project

Taking (some) Pain out of Multithreading

Download v0.7.1 (48k)

v0.7.1 Only makes a change to the example project for the sake of Xcode 3.2.

ThreadWorker is a class whose sole class-level method makes it easy to offload a task to another thread and notify your application when you've completed the task. Inspriation comes from Java's SwingWorker class. Creating Multithreaded applications with Objective-C in Mac OS X's Cocoa framework is easier than raw C code, but there are still some difficulties that ThreadWorker will help you overcome.

With the advent of libdispatch (Grand Central Dispatch) and blocks in Mac OS X 10.6 Snow Leopard, this style of multithreading may be on its way out, but in the meantime, I still find it handy!

Follow the file release RSS feed...

Be sure to copy the ThreadWorker.h and ThreadWorker.m files to your project directory.

Here is an example of how you would call ThreadWorker from your class. There is more information on the API page.

    [ThreadWorker workOn:self 
                  withSelector:@selector(longTask:) 
                  withObject:userInfo
                  didEndSelector:@selector(longTaskFinished:)];

The longTask method in self will then be called and should look like this:

     - (id)longTask:(id)someData
     {
         // Do something that takes a while and uses 'someData' if you want
         // ...
 
         return userInfo; // Will be passed to didEndSelector
     }  

Or view ThreadWorker.h or ThreadWorker.m directly.

Enjoy!

A Note About Public Domain

I have released this software into the Public Domain. That means you can do whatever you want with it. Really. You don't have to match it up with any other open source license — just use it. You can rename the files, do whatever you want. If your lawyers say you have to have a license, contact me, and I'll make a special release to you under whatever reasonable license you desire: MIT, BSD, GPL, whatever.