在我的 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) 所示的一致。
有人可以向我解释一下它是否会生成保留周期吗?如果是的话怎么解决?
最佳答案
它确实创建了一个保留周期:您的节点在 flattenElementsCache
中保留对其自身的引用。
您可以删除标有 (1) 的行,并将循环更改为:
for child in children {
flattenElementsCache.append(child)
flattenElementsCache.append(contentsOf: child.flattenElements)
}
关于ios - Swift 保留周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47551099/