Why would I ever use unowned self?

I believe that using unowned adds to the risk than using weak self. Mistakes do happen and one example of it would be starting an API call in a view controller, let it wait for the response to arrive and suddenly popping that view controller may cause it to get deallocated (If there are no strong references to it). By the time when the response arrives, our view controller object would be gone, and our app will crash on our face. It is up to us to decide which one to use in which place.

As Jeremy pointed out, unowned does not have the responsibility to keep track of the reference count, so it has ever so slight performance advantage over strong and weak.


unowned has a marginal performance advantage over weak because the runtime doesn't have to keep track of the reference to turn it into nil when the object goes away.

In respect of retain cycles (well, strong reference cycles), neither weak nor unowned creates a strong reference (in pre ARC terms, neither increments the retain count) so there is no danger of a reference cycle, in fact, that is why you need to specify weak or unowned for self in closures.

Also, with unowned you can use the reference as a non optional, so you don't have to put any code in the closure to unwrap it.

I always use weak unless there is a really good performance reason not to.

NB in your code, I do not think either is necessary because the closure is not escaping i.e. The reference to it taken in the function call foo does not persist after the end of foo's scope.

Tags:

Ios

Swift

Swift3