简体   繁体   English

快速[弱自我]引起的内存泄漏

[英]A memory leak caused by [weak self] in swift

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
}

leak find in DispatchQueue.main.async { [weak self] in line through instruments. 通过仪器在DispatchQueue.main.async { [weak self] in找到泄漏。 It can be fixed by use [unowned self] , but I can't guarantee the nil situation. 可以通过使用[unowned self]进行修复,但我不能保证这种情况不会出现。

I'm just curious the reason of memory leak, why would [weak self] cause a memory leak? 我只是很好奇内存泄漏的原因,为什么[weak self]会导致内存泄漏? It's not a nested closure, the capture looks fine... Also, why use [unowned self] can fix this? 它不是嵌套的闭包,捕获看起来很好...而且,为什么使用[unowned self]可以解决此问题?

'weak' reference is supposed to take more resources, than 'unowned'. “弱”引用应该比“无人”引用占用更多资源。 At runtime when the object that is referenced weekly gets deallocated, there is a process of resetting 'weak' pointers to this object to 'nil'. 在运行时,如果每周引用的对象被释放,则有一个将指向该对象的“弱”指针重置为“ nil”的过程。 On the other hand, 'unowned' pointer is not being kept track of like this. 另一方面,不会像这样跟踪“无主”指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM