> ## Content Index
> Fetch the complete content index at: https://williamboles.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Polling with NSOperation
- URL: https://williamboles.com/allow-nsoperation-to-live-forever-well-until-you-cancel-it/
- Published: 2011-05-16T17:55:00.000Z
- Updated: 2026-09-26T16:34:36.000Z
- Description: Sometimes, when you need to know, you need to poll. Here, we look at building a polling mechanism using `NSOperation`.
- Author: William Boles
- Tags: 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 were to use `NSOperationInvocation`, but things got messy quickly, so I decided to reach for its big brother [NSOperation](https://developer.apple.com/documentation/foundation/operation?ref=williamboles.com).

![Photo of workers on polls](https://storage.ghost.io/c/b9/b4/b9b42214-5933-4584-8e56-9ee8ca21d23b/content/images/size/w1000/2019/11/workers-on-polls-min-1.jpg)

## 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 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 `TRUE`, which in turn sets `_keepListening` to `NO`, causing the `while` loop to exist and so destroying the `NSOperation` object.