What is the correct way to release a GCD dispatch queue property?

后端 未结 4 945
耶瑟儿~
耶瑟儿~ 2021-02-18 19:18

I\'m using a dispatch_queue which is accessed through a property of its owner, like this:

@property (nonatomic, assign) dispatch_queue_t queue;

4条回答
  •  心在旅途
    2021-02-18 19:58

    The following is stolen from the developer documentation:

    Dispatch queues and other dispatch objects are reference-counted data types. When you create a serial dispatch queue, it has an initial reference count of 1. You can use the dispatch_retain and dispatch_release functions to increment and decrement that reference count as needed. When the reference count of a queue reaches zero, the system asynchronously deallocates the queue.

    When your application no longer needs the dispatch queue, it should release it with the dispatch_release function. Any pending blocks submitted to a queue hold a reference to that queue, so the queue is not deallocated until all pending blocks have completed.

    Note: You do not need to retain or release any of the global dispatch queues, including the concurrent dispatch queues or the main dispatch queue. Any attempts to retain or release the queues are ignored.

    So anywhere you would use -retain use dispatch_retain and anywhere you would use -release use dispatch_release.

    Dispatch queues follow the same general memory management conventions as objective-c objects. And they won't be dealloc'ed until all blocks queued are finished.

    If you do want a way to shut down a dispatch queue: There's no way to cancel all enqueued blocks via any sort of API, so they always must run to completion. One way to expedite this process is to have a BOOL variable in the class managing the dispatch queue: _isValid. When you want to shut down the queue, you can set _isValid to NO. All blocks submitted to the queue should first check _isValid before doing any work.

    A side comment: It may be more appropriate to use NSOperationQueue. See Chris Hanson's blog post.

提交回复
热议问题