斯威夫特保留周期

时间:2017-11-29 10:56:00

标签: ios swift memory-leaks retain-cycle

在我的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)所示。

有人可以向我解释它是否会产生保留周期吗?如果是的话,你是如何解决的?

2 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

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

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

但我不确定是否出现参考周期