Continuing on from Swift: The rules of being weak, this post considers the rules of employing weak's ally in the fight against strong reference cycles, unowned.
Rules of the unowned keyword
Here are the rules of the unowned keyword- it can be used inside classes, structs, enums and protocols
- it can be used with constants, variables and properties
- the variables and properties it is used with must not be optionals
- it cannot be used to declare (or set) variables that are non-class types, for example unowned var a:String would raise a compiler error (as will all of Swift's own types, since they are all structs and enums)
unowned var a:Person = Person(name: "John Appleseed") // nil
Don't be a crash test dummy
Testing Apple's code examples of a strong reference cycle won't crash your app if you simply remove the unowned keyword. This is a warning sign that awareness of strong reference cycles needs to be learnt, rather than discovered in research after a crash.The major indicator that you need to employ unowned or weak keywords is that you have two class instances owning (or referencing) one another in their properties or in variables. In which case you need to make one of those references either weak or unowned.
Tips for testing unowned
A couple of tips for testing the deintiliazation:- you must use the Simulator, not a Playground, in order to see the deinitialization taking place
- even with strong references, ARC deinitializes as soon as possible, which means that if you place the variable declarations in the same method as the assignments then once that method has ended the instances will be released and deinitialized anyway without even setting the strong references to nil
Comments
Post a Comment