Resolving Strong Reference Cycles for Closures
You resolve a strong reference cycle between a closure and a class instance by defining a?capture list?as part of the closure’s definition. A capture list defines the rules to use when capturing one or more reference types within the closure’s body. As with strong reference cycles between two class instances, you declare each captured reference to be a weak or unowned reference rather than a strong reference. The appropriate choice of weak or unowned depends on the relationships between the different parts of your code.
NOTE
Swift requires you to write?self.someProperty?or?self.someMethod()?(rather than just?someProperty?or?someMethod()) whenever you refer to a member of?self?within a closure. This helps you remember that it’s possible to capture?self?by accident.
Defining a Capture List
Each item in a capture list is a pairing of the?weak?or?unowned?keyword with a reference to a class instance (such as?self) or a variable initialized with some value (such as?delegate = self.delegate!). These pairings are written within a pair of square braces, separated by commas.
Place the capture list before a closure’s parameter list and return type if they are provided:
If a closure does not specify a parameter list or return type because they can be inferred from context, place the capture list at the very start of the closure, followed by the?in?keyword:
Weak and Unowned References
Define a capture in a closure as an unowned reference when the closure and the instance it captures will always refer to each other, and will always be deallocated at the same time.
Conversely, define a capture as a weak reference when the captured reference may become?nil?at some point in the future. Weak references are always of an optional type, and automatically become?nil?when the instance they reference is deallocated. This enables you to check for their existence within the closure’s body.
NOTE
If the captured reference will never become?nil, it should always be captured as an unowned reference, rather than a weak reference.
?
總結
以上是生活随笔為你收集整理的Resolving Strong Reference Cycles for Closures的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring MVC 中的 contro
- 下一篇: ConstraintLayout如何优化