zoukankan      html  css  js  c++  java
  • 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:

    1. lazy var someClosure: (Int, String) -> String = {
    2. [unowned self, weak delegate = self.delegate!] (index: Int, stringToProcess: String) -> String in
    3. // closure body goes here
    4. }

    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:

    1. lazy var someClosure: () -> String = {
    2. [unowned self, weak delegate = self.delegate!] in
    3. // closure body goes here
    4. }

    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.

  • 相关阅读:
    【STL】栈stack
    【简单思考】noip2010提高组 乌龟棋
    【水】noip2010提高组 机器翻译
    【dp概率与期望】pattern
    【快速幂+中等难度】Calculation 哈工大HITOJ2901
    hdu--4502--dp
    hdu--4432--好久没做题了.
    hdu--5019--开始参加bc了
    字符串排列后匹配
    输出n的全排列的字典序编号为k的全排列
  • 原文地址:https://www.cnblogs.com/feng9exe/p/9022410.html
Copyright © 2011-2022 走看看