快速[弱自我]导致的内存泄漏

时间:2018-09-14 09:24:54

标签: swift memory-leaks closures weak-references

func addAdditionalElement(_ additionalSelectedElementsIDs: [String], startX: CGFloat, containerView: UIView, viewHeight: CGFloat) -> CGFloat {
    var totalWidth = startX

    if additionalSelectedElementsIDs.count > 0 {

        let paddingBeforeLabel = (totalWidth==0 ? 0:paddingBetweenLabels)
        totalWidth += paddingBeforeLabel
        var countLabel = createLabel("+\(additionalSelectedElementsIDs.count)", shouldStrikethrough: false)
        if let filter = filter as? DsFilter {
            if filter.isRAOptimization() {
                countLabel = createLabel("...", shouldStrikethrough: false)
            }
        }
        countLabel.frame = CGRect(x: totalWidth, y: 0, width: countLabel.frame.size.width, height: viewHeight)
        countLabel.layer.cornerRadius = countLabel.frame.size.height / 2
        addLabel(countLabel, containerView: containerView)
        DispatchQueue.main.async { [weak self] in
            guard let isSubset = self?.filter.isSelectedElementsSubset(elementsIDs: additionalSelectedElementsIDs) else { return }
            self?.updateLabelSelectedState(countLabel, isTemporarySelected: !isSubset)
        }
        totalWidth += countLabel.frame.size.width
    }
    return totalWidth
}
通过仪器在DispatchQueue.main.async { [weak self] in行中进行

泄漏查找。可以使用[unowned self]进行修复,但我不能保证完全没有问题。

我很好奇内存泄漏的原因,为什么[weak self]会导致内存泄漏?它不是嵌套的闭包,捕获看起来不错... 另外,为什么使用[unowned self]可以解决此问题?

1 个答案:

答案 0 :(得分:0)

“弱”引用应该比“无人”占用更多资源。在运行时,如果每周引用的对象被释放,则有一个将指向该对象的“弱”指针重置为“ nil”的过程。另一方面,不会像这样跟踪“无主”指针。