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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With