【问题标题】:Swift Retain CyclesSwift 保留周期
【发布时间】:2018-05-13 01:30:13
【问题描述】:

在我的 iOS 应用中

class Node {
    var value: String
    var isExpanded: Bool
    var children: [Node] = []

    private var flattenElementsCache: [Node]!

    // init methods

    var flattenElements: [Node] {
        if let cache = flattenElementsCache {
            return cache
        }
        flattenElementsCache = []
        flattenElementsCache.append(self) // (1) <-- Retain Cycle???
        if isExpanded {
            for child in children {
                flattenElementsCache.append(contentsOf: child.flattenElements)
            }
        }
        return flattenElementsCache;
    }
}

使用 Instruments,我观察到一些内存泄漏,我认为问题符合 (1) 所示。

如果它产生了一个保留周期,谁能向我解释一下?如果是,您如何解决?

【问题讨论】:

    标签: ios swift memory-leaks retain-cycle


    【解决方案1】:

    它确实创建了一个保留循环:您的节点在flattenElementsCache 中保留了对自身的引用。

    您可以删除 (1) 标记的行,而是将循环更改为:

    for child in children {
        flattenElementsCache.append(child)
        flattenElementsCache.append(contentsOf: child.flattenElements)
    }
    

    【讨论】:

      【解决方案2】:

      显然,要解决它,请使用弱引用而不是强引用。

      class Node {
          var links: [Node?] = []
          init() {
              weak var weakSelf = self
              links.append(weakSelf)
          }
      }
      

      但我不确定是否出现引用循环

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-15
        • 2015-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-11
        • 2016-05-06
        • 2012-09-29
        相关资源
        最近更新 更多