Is it dangerous to set off an autoreleased NSOperationQueue?

后端 未结 4 1664
陌清茗
陌清茗 2020-12-10 14:03

I have a task that takes a rather long time and should run in the background. According to the documentation, this can be done using an NSOperationQueue. Howeve

相关标签:
4条回答
  • 2020-12-10 14:14

    There's nothing in the documentation to say what happens when the NSOperationQueue is released. It would be safest to assume there's no guarantee that theTask will get executed.

    0 讨论(0)
  • 2020-12-10 14:25

    There's no guarantee that it's safe to release an NSOperationQueue while it's still working. I suspect it probably is safe and this guarantee will probably be added someday, but it isn't there now. However, the equivalent Grand Central Dispatch API does guarantee that you can safely release its queues when you're done using them and it will keep them around as long as it needs them. So if you're on a platform with GCD, you can use that to be sure it won't blow up in the meantime.

    Alternatively, you could create a wrapper class that checks if a queue is finished and releases both the queue and itself when the queue is finished.

    0 讨论(0)
  • 2020-12-10 14:28

    I would have guessed that an NSOperationQueue releases its tasks when it's released, but I've noticed that the tasks do complete and dealloc even if I release the queue immediately after adding the task. That said, I don't think I'd rely on that behavior - there's more to gain by storing the NSOperationQueue in an instance variable (and releasing it in dealloc). An instance variable will give you a way to call other methods on the queue (cancelAllOperations, setSuspended, etc).

    0 讨论(0)
  • 2020-12-10 14:28

    Can't you use the [NSOperation mainQueue] object so that you don't need to worry about autoreleasing it? If you only need to add one task that seems to make the most sense to me.

    http://developer.apple.com/mac/library/documentation/Cocoa/Reference/NSOperationQueue_class/Reference/Reference.html#//apple_ref/doc/uid/TP40004592-RH2-SW21

    0 讨论(0)
提交回复
热议问题