Polling with NSOperation

May 16th, 2011 1 min read

Recently, I was writing an application that analysed audio input and updated an audio visualiser on screen. Running everything on the main thread just ground UI responsiveness down, so I decided to spin off the audio capture into a separate thread. My first thought was to use NSInvocationOperation, but things got messy quickly, so I decided to reach for its big brother NSOperation.

Photo of workers on poles

NSOperation

I decided to subclass NSOperation and override main, allowing me to keep the thread alive until I didn't need it:

- (void)main
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    @try
    {
        // more setup code

        while (_keepListening) // _keepListening is an instance variable set to YES by default
        {
            if (self.isCancelled)
            {
                _keepListening = NO;
                // more clean-up code
            }
            else
            {
                // do something
            }
        }
    }
    @catch (NSException *e)
    {
        // freak out!!!
    }
    @finally
    {
        [pool drain];
    }
}

Now I have a thread that runs until I change the _keepListening variable to NO, which I do when the user presses the stop recording button:

[_queue cancelAllOperations]; // _queue is an instance variable that the above NSOperation was added to

The above then makes the if statement in the while evaluate to YES, which in turn sets _keepListening to NO, causing the while loop to exit and so destroying the NSOperation object.

What do you think? Let me know by getting in touch on Mastodon or Bluesky.

Keep reading