Properly dealloc NSOperationQueue
Asked Answered
I

1

11

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?

Incongruity answered 13/1, 2011 at 15:44 Comment(0)
S
10

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.

Stowell answered 15/1, 2011 at 18:9 Comment(5)
Thanks for the answer! So I can be sure that the _queue will be properly released and there will be no leak even if the dealloc is called because of a didReceiveMemoryWarning, not just on quit?Incongruity
Yes, you'll be fine no matter what the reason dealloc is running. Once the operations clear out, the queue will be deallocated. (Unless, of course, some other object has retained the queue.)Stowell
This will work unless isSuspended is set to YES. If it is, the queue won't release the operations in the queue. For safety, if you ever call setSuspended on your queue, remember to reset it to NO after canceling the operations.Adali
Can anyone elaborate a little on the fate of the currently executing operations, when NSOperationQueue itself is deallocated? Will the queue itself wait for the finish of its operations (synchronously) or dealloc them mid-executing, or otherwise forcibly move them to the "finished" state, so it can remove and delete them?Zucker
The queue will not be deallocated until all its operations are finished (or cancelled)Stowell

© 2022 - 2024 — McMap. All rights reserved.