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.

  • 相关阅读:
    洛谷P1265 公路修建(Prim)
    洛谷P1144 最短路计数(SPFA)
    洛谷P1198 [JSOI2008]最大数(BZOJ.1012 )
    洛谷P2879 [USACO07JAN]区间统计Tallest Cow
    洛谷P1886 滑动窗口(POJ.2823 Sliding Window)(区间最值)
    洛谷P2105 K皇后
    洛谷P3373 [模板]线段树 2(区间增减.乘 区间求和)
    洛谷P2982 [USACO10FEB]慢下来Slowing down(线段树 DFS序 区间增减 单点查询)
    洛谷P1784 数独
    洛谷 P2574 XOR的艺术(线段树 区间异或 区间求和)
  • 原文地址:https://www.cnblogs.com/feng9exe/p/9022410.html
Copyright © 2011-2022 走看看