Swift 3 & iOS 10 false memory leak bug

北战南征 提交于 2019-12-14 03:46:09

问题


There seems to be a (false) memory leak bug in Xcode 8 when using with iOS 10 & Swift 3.

The following code reports a memory leak in Instruments and the Xcode 8 memory debugger:

class SomeClass: NSObject {
    var view: SomeView!

    deinit {
        print("SomeClass deinit")
    }
}

class SomeView: UIView {
    weak var reference: SomeClass?

    deinit {
        print("SomeView deinit")
    }
}

class ViewController: UIViewController {
    var someProperty: SomeClass?

    override func viewDidLoad() {
        super.viewDidLoad()

        let c = SomeClass()
        let v = SomeView()
        c.view = v
        v.reference = c

        someProperty = c
    }
}

回答1:


I've tried different variations to confirm it's indeed a bug and my findings are:

  1. When you don't assign c in the sample code to someProperty, both instances will print the string in their respective deinits. A true strong reference cycle won't deinit.
  2. When SomeClass doesn't inherit from NSObject, this bug doesn't happen.
  3. When using Swift 2.2, this doesn't happen.
  4. When using iOS 9-, this doesn't happen.
  5. Once someProperty is set to nil somewhere in the code, both instances are deinited. Xcode 8 memory debugger confirms there are no memory leaks. However in Instruments, this change isn't reflected--rightfully so, since a real memory leak probably won't be resolved.

FYI, this doesn't happen only when it's assigned to a property of UIViewController. I originally found out about this behavior in a singleton object.




回答2:


Seems fixed with iOS 10.3 (first beta) and Xcode 8.3 (first beta).



来源:https://stackoverflow.com/questions/39886126/swift-3-ios-10-false-memory-leak-bug

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!