Featured post

Weak vs Unowned Self in Swift


If you’re programming in the pre-ARC era, you manually release your objects to avoid memory leaks. And I remember when ARC was introduced, I thought, whew, finally I wouldn’t care anymore on releasing my objects. But I was wrong, you still have to be careful on how you use referencing, and you may be like me, I thought, okay, so there’s a bunch of new concepts to follow after all, I thought ARC will simplify stuff. It takes a little bit of study, to really understand how it works and one really recurring problem I come across is the difference between weak and unowned self. So as they say,

A weak reference is a reference that does not keep a strong hold on the instance it refers to, and so does not stop ARC from releasing the referenced instance.

However in unowned self, the object cannot exist without the reference. So for example an object, we want a property which will always be populated but we also want it to be weak, so meaning unowned is a weak reference that needs to be populated. I’m sure you’re still a bit confuse, so I’ll try to explain by using an example.



With this example, if we don’t specify unowned, it will cause a reference cycle, since by default properties are strong. And if we use weak on the person variable of class BankAccount, logically a bank account cannot live without a reference of a person, so that’s why it’s important that it has a reference to a person. Notice also that the person is required when initializing a BankAccount, this emphasize that, unowned properties are weak but required to have a value.

In summary, I like to show you this concept in an illustration


Comments