Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properly dealloc NSOperationQueue

I'd like to know what is the proper way to dealloc an ivar NSOperationQueue in case it has still some operations running, which can typically occur when the user suddenly quits the app. In some examples I saw the waitUntilAllOperationsAreFinished was used, like this:


- (void)dealloc {
    [_queue cancelAllOperations];
    [_queue waitUntilAllOperationsAreFinished];
    [_queue release];
    ...

however many suggest to avoid doing so since it would hang the run loop. So what is the proper way to release the _queue? And what happens if I don't wait for operations to be finished and just go on with the release?

like image 810
Tomas Camin Avatar asked Jan 13 '11 15:01

Tomas Camin


1 Answers

In almost all cases, calling cancelAllOperations will be sufficient. The only time you need to call waitUntilAllOperationsAreFinished is if you actually need to ensure that those operations are done before you move on.

For example, you might do so if the operations are accessing some shared memory, and if you don't wait then you'll end up with two threads writing to that shared memory at the same time. However, I can't think of any reasonable design that would protect shared memory by causing a blocking delay in a dealloc method. There are far better sychronization mechanisms available.

So the short answer is this: you don't need to wait for all operations to finish unless there's some reason your application specifically needs it.

like image 101
BJ Homer Avatar answered Oct 16 '22 04:10

BJ Homer