ThreadWorker class to help with multithreading

rharder

Do not read this sign.
After much hair-pulling I finally created a great little class called ThreadWorker which fills the hole in Objective-C that SwingWorker fills in Java.

You can throw off work in another thread and then be notified in your primary thread when the long task is finished.

Anyhoo, check it out if you need easy multithreading (and everyone does):

http://www.iharder.net/macosx/threadworker

-Rob
 
I just thought up a useful pattern that gives you the advantage of multithreading with the convenience of keeping user-invoked code (like from an NSButton) in the "- (IBAction)..." method.

You can branch based on the value of the sender argument like this:
Code:
- (IBAction)okayButtonPressed: (id)sender
    {
        if( sender == _OkayButton )
        {
            // Event-dispatching thread
            // called when user hits button
            [ThreadWorker workOn:self
                          withSelector:@selector(okayButtonPressed: )
                          withArgument:self
                          didEndTarget:self
                          didEndSelector:@selector(okayButtonPressed: )];

        }   // end if: initial button press

        else if( sender == self )
        {
            // Code to run in another thread
            // ...

        }   // end else if: other thread

        else
        {
            // Called when thread is finished
            // ...

        }   // end else: thread finished
    }

Keep threadin'.

-Rob
 
Back
Top