本文介绍了斯威夫特 3 &iOS 10 错误内存泄漏错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Xcode 8 中与 iOS 10 & 一起使用时似乎存在(错误的)内存泄漏错误斯威夫特 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:
- 当您没有将示例代码中的
c
分配给someProperty
时,两个实例都将在各自的deinit
中打印字符串.真正的强引用循环不会取消. - 当
SomeClass
不继承自NSObject
时,不会发生此错误. - 使用 Swift 2.2 时,不会发生这种情况.
- 使用 iOS 9- 时,不会发生这种情况.
- 一旦
someProperty
在代码中的某处设置为nil
,两个实例都被deinit
ed.Xcode 8 内存调试器确认没有内存泄漏.然而,在 Instruments 中,这种变化并没有反映出来——这是理所当然的,因为真正的内存泄漏可能不会得到解决.
- When you don't assign
c
in the sample code tosomeProperty
, both instances will print the string in their respectivedeinit
s. A true strong reference cycle won't deinit. - When
SomeClass
doesn't inherit fromNSObject
, this bug doesn't happen. - When using Swift 2.2, this doesn't happen.
- When using iOS 9-, this doesn't happen.
- Once
someProperty
is set tonil
somewhere in the code, both instances aredeinit
ed. 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 错误内存泄漏错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!