If your delegate is managing a ‘heavy’ resource, like a file handle, clean that up in -URLSession:didBecomeInvalidWithError:
This only solves one part of the problem. The other is the following one :
My delegate object is actually a component in a component hierarchy. I'm writing a unit test making sure that the hierarchy doesn't contain any retain cycle. This code works as follow :
instantiate the root object in a local scope,
iterate over all the sub-objects and create weak pointers to them in the parent scope
exit the local scope
test that all the weak pointers have been set to nil.
Without any guarantee over the time at which the URLSession will release its delegate, there's nothing i can wait upon to make sure no retain cycle exists (because the URLSession itself creates that retain cycle).
Now i got your point, and i think my solution will be to use an intermediate struct as a URLSessionDelegate, containing nothing but a weak pointer to the component, and simply forwarding all the calls to it. (and actually breaking the strong retain created by the URLSession).
It will look hacky, but without more commitment on that side of the URLSession api, there isn't a lot more i can do.