ios - Swift 保留周期

标签 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) 所示的一致。

有人可以向我解释一下它是否会生成保留周期吗?如果是的话怎么解决?

最佳答案

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

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

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

关于ios - Swift 保留周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47551099/

相关文章:

ios - Swift 中 UIViewController 初始化的疯狂行为

ios - 使用未解析的标识符 - 使用 Swift Project 2 进行应用程序开发

ios - 从 Firebase 检索用户经纬度后添加注释

ios - 动画不会在 UITableView 的 backgroundView 上被杀死

c++ - 正在释放的指针未分配给所有对象的问题!

ios - 将 UIImage 转换为 NSData 并在 Swift 中转换回 UIImage?

ios - 确定 `UIView` 是从 XIB 加载还是从代码实例化

ios - CoreStore 分段列表监视器如何在运行时指定 .where 子句

ios - UITabBarItem 内存泄漏

ios - 弹出 UIViewController 后,MKMapView autorelease 不调用 dealloc