斯威夫特3& iOS 10错误的内存泄漏错误 [英] Swift 3 & iOS 10 false memory leak bug

查看:74
本文介绍了斯威夫特3& iOS 10错误的内存泄漏错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当与iOS 10及更高版本一起使用时,Xcode 8中似乎存在(虚假)内存泄漏错误.雨燕3.

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

以下代码报告了Instruments和Xcode 8内存调试器中的内存泄漏:

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
    }
}

推荐答案

我尝试了各种变体来确认它确实是一个错误,而我的发现是:

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

  1. 如果未在示例代码中将c分配给someProperty,则两个实例将在各自的deinit中打印字符串.真正的强参考周期不会取消初始化.
  2. SomeClass不继承自NSObject时,不会发生此错误.
  3. 使用Swift 2.2时,不会发生这种情况.
  4. 使用iOS 9-时,不会发生这种情况.
  5. 一旦在代码中的某个位置将someProperty设置为nil,就会对两个实例进行deinit运算. Xcode 8内存调试器确认没有内存泄漏.但是,在Instruments中,此更改未得到反映-正确地如此,因为实际的内存泄漏可能无法解决.
  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.

仅供参考,仅当将其分配给UIViewController属性时,才会发生这种情况.我最初是在单例对象中发现此行为的.

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.

这篇关于斯威夫特3& iOS 10错误的内存泄漏错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆