Allow NSOperation to live forever (well, until you cancel it)!

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 until the UI fell apart and only worked in jumps 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.

NSOperation

I decided to subclass to NSOperation and override the main method 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 and sets _keepListening to NO so destroying the NSOperation object.