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?

Tomas Camin
  • 9,996
  • 2
  • 43
  • 62

1 Answers1

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.

BJ Homer
  • 48,806
  • 11
  • 116
  • 129
  • 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? – Tomas Camin Jan 15 '11 at 18:49
  • 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.) – BJ Homer Jan 16 '11 at 06:53
  • 1
    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. – vfn Apr 07 '11 at 02:20
  • 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? – Motti Shneor Oct 24 '15 at 07:23
  • 1
    The queue will not be deallocated until all its operations are finished (or cancelled) – BJ Homer Oct 24 '15 at 14:59