What property should I use for a Dispatch Queue after ARC?

前端 未结 5 621
情深已故
情深已故 2020-12-04 15:28

I maintain a dispatch queue as a property with my view controller. I create this queue once in my view controller\'s init method, and reuse a few times for some background t

5条回答
  •  悲哀的现实
    2020-12-04 15:58

    TL;DR: dispatch_queue_t is an Objective C object now and can be managed with ARC.

    I haven't tested how far back this is true, but using the iOS 7 SDK and Xcode 5, dispatch_queue_t is an object type. I am declaring a property for a queue as

    @property (nonatomic, strong) dispatch_queue_t syncQueue;
    

    The compiler is happy and everything works as expected. I know definitively that this used to not work in iOS 4 or 5 (pre-ARC it was retain instead of strong). I dug into the definition for dispatch_queue_t and found this:

    /*!
     * @typedef dispatch_queue_t
     *
     * @abstract
     * Dispatch queues invoke blocks submitted to them serially in FIFO order. A
     * queue will only invoke one block at a time, but independent queues may each
     * invoke their blocks concurrently with respect to each other.
     *
     * @discussion
     * Dispatch queues are lightweight objects to which blocks may be submitted.
     * The system manages a pool of threads which process dispatch queues and
     * invoke blocks submitted to them.
     *
     * Conceptually a dispatch queue may have its own thread of execution, and
     * interaction between queues is highly asynchronous.
     *
     * Dispatch queues are reference counted via calls to dispatch_retain() and
     * dispatch_release(). Pending blocks submitted to a queue also hold a
     * reference to the queue until they have finished. Once all references to a
     * queue have been released, the queue will be deallocated by the system.
     */
    DISPATCH_DECL(dispatch_queue);
    

    By the sounds of that, it shouldn't work, so I checked the definition of DISPATCH_DECL and found this, which explains everything:

    /*
     * By default, dispatch objects are declared as Objective-C types when building
     * with an Objective-C compiler. This allows them to participate in ARC, in RR
     * management by the Blocks runtime and in leaks checking by the static
     * analyzer, and enables them to be added to Cocoa collections.
     * See  for details.
     */
    

提交回复
热议问题