I’m using Apple’s Network framework to implement a UDP client using NWConnection, and I have a question regarding the lifecycle of the DispatchQueue associated with an NWConnection instance.
Let's assume I have an NWConnection instance, and I associate it with a dispatch queue using the start(queue:) API, such that network OS events for the NWConnection instance can be delivered to this queue.
My understanding is that this association would result in NWConnection holding a strong reference to the DispatchQueue object.
Now, I perform some I/O (send/receive) on the NWConnection instance and immediately perform the following steps. Also, assume that the completion closures for those I/O operations do not capture or otherwise retain the NWConnection.
- Call connection.cancel() and then release my last strong reference to the NWConnection.
- Without waiting for the connection to transition to the .cancelled state, I also release my last strong reference to the associated DispatchQueue.
My question is:
Does NWConnection, during its teardown, retain the DispatchQueue until the cancellation completions for all pending I/O operations associated with the connection have been delivered/executed, given that the application no longer holds any strong references to either the NWConnection or the DispatchQueue?
Or, once cancel() is called, does NWConnection immediately release its reference to the DispatchQueue, in which case whether the pending callbacks are ultimately executed depends on whether the application has kept the queue alive?