Polling with NSOperation

May 16th, 2011
#Concurrency

Recently I was writing an application that analysed audio input and updated an audio visualiser on screen. Running everything in the main thread just ground UI responsiveness down so I decided to spin off the audio capture into a separate thread. My first thoughts where to use NSOperationInvocation and run across this tutorial by Wim Haanstra on how to keep a thread alive. This solution worked but the code that I had produced using it felt messy so I decided to experiment myself.

Photo of workers on polls

NSOperation

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

- (void)main{
    @try {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        //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
            }
        }

        [pool drain];
    }@catch (NSException * e) {
        //freak out!!!
    }	
}

Now I have a thread that runs until I change the _keepListening variable to NO which is did 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 TRUE which in turn sets _keepListening to NO causing the while loop to exist and so destroying the NSOperation object.

What do you think? Let me know by getting in touch on Twitter - @wibosco

William Boles

William has been an iOS developer since 2010, after all these years he just hopes that the String API will stop changing now.