Search code examples
objective-cdelegatesnsthreadquartz-composer

Asynchronously run an NSThread, but with a delegate?


I want to launch a daemon on new thread, to my program doesn't lock up while waiting for input from the daemon, but I need a way for the main program to get information back from the daemon. I've used NSThread to fire off a new thread, but I don't see how to use a delegate with NSThread.

For more context, I'm working on a custom patch for Quartz Composer that will receive data from the network. The idea is that a second thread could run the daemon, and on each frame, I'd grab the new data from an ivar set by a delegate method when the daemon thread received new data.. all the while, the composition runs along with no interruption.

Can I do this with NSThread? Is there a better way I should be looking at?


Solution

  • Edit: If you want the delegate callbacks to occur on the main thread, use this pattern: [delegate performSelectorOnMainThread:@selector(threadDidSomething:) withObject:self waitUntilDone:NO]

    Here you go. I believe this is self-explanatory, but if not, just let me know. Please note: I just wrote this code based on the API, but have not tested it, so take caution.

    @protocol ThreadLogicContainerDelegate <NSObject>
    - (void)threadLogicContainerDidStart:(ThreadLogicContainer*)theThreadLogicContainer;
    - (void)threadLogicContainerDidFinish:(ThreadLogicContainer*)theThreadLogicContainer;
    @end
    
    @interface ThreadLogicContainer
    
    - (void)doWorkWithDelegate:(id<ThreadLogicContainerDelegate>)delegate;
    
    @end
    
    @implementation ThreadLogicContainer
    
    - (void)doWorkWithDelegate:(id<ThreadLogicContainerDelegate>)delegate
    {
        @autoreleasepool
        {
            [delegate threadLogicContainerDidStart:self];
    
            // do work
    
            [delegate threadLogicContainerDidFinish:self];
        }
    }
    
    @end
    
    
    @interface MyDelegate <ThreadLogicContainerDelegate>
    @end
    
    @implementation MyDelegate
    - (void)threadLogicContainerDidStart:(ThreadLogicContainer*)theThreadLogicContainer
    {}
    - (void)threadLogicContainerDidFinish:(ThreadLogicContainer*)theThreadLogicContainer
    {}
    @end
    

    Sample usage:

    ThreadLogicContainer* threadLogicContainer = [ThreadLogicContainer new];
    [NSThread detachNewThreadSelector:@selector(doWorkWithDelegate:)
                             toTarget:threadLogicContainer
                            withObject:myDelegate];
    

    reference: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSThread_Class/Reference/Reference.html