Weak vs Strong IBOutlets

Hi @pulkitap!

The best practice is to start with a strong reference and move to weak as needed. When determining if a property should be strong or weak, look into Apple’s Automatic Reference Counting (ARC) first introduced in iOS 5 and 2011. You can learn more about this topic with the following article:

https://www.raywenderlich.com/966538-arc-and-memory-management-in-swift

And/or with the following video course:

https://www.raywenderlich.com/1940727-advanced-swift-memory-management

Understanding Swift memory management and reference counting will help you decide whether an IBOutlet should be weak or strong. You can use the initializer and de-initializer to verify whether class instances have the correct allocation/deallocation behavior with the reference count expectations. Beyond that, running Allocations and Leaks instruments against your application can help you find less obvious memory leaks.

Xcode understands that properties are referenced from the Interface Builder with the IBOutlet property declaration. Beyond that, the fundamentals of Automatic Reference Counting (ARC) and memory management in Swift still applies.

Every view controller has a strong reference to a view it manages. If you open UIViewController, you can find that view is declared as strong. You want a strong reference to mitigate invalid memory deallocation. When a view is alive, you should ask if its subviews should also be alive? In most cases, this would be a yes. Hence, the view keeps a strong reference to its subviews. All in all, the compiler needs to know when memory deallocation of a class instance is safe to mitigate memory overflow.

As a bonus resource, if you’d like to watch Chris Lattner introduce Automatic Reference Counting from about nine years ago, you can watch his introduction of the memory management system here from 2011:

1 Like