Swift 3.1 中 ARC 内存管理方面 weak 和 unowned 的区别

Difference Between weak & unowned in respect to ARC memory management in Swift 3.1

我正在研究 Swift,我对 unownedweak 关键字在 Swift.

中用于内存管理的用法有点困惑

任何人都可以帮助我了解在哪里使用 unowned 吗?

提前致谢!

根据苹果文档

开发者网站上有一些很好的例子,查看这个link

就块而言,根据 Apple Docs:

Define a capture in a closure as an unowned reference when the closure and the instance it captures will always refer to each other, and will always be deallocated at the same time.

Conversely, define a capture as a weak reference when the captured reference may become nil at some point in the future. Weak references are always of an optional type, and automatically become nil when the instance they reference is deallocated. This enables you to check for their existence within the closure’s body.

To conclude Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialization.”

最重要的区别是无主变量在Swift中非常危险。

weak is an optional type, unowned is NOT.

这意味着您可以创建使用 weak 作为逻辑的一部分的代码。 (想想只有当视图控制器仍在屏幕上显示时才会发生的异步操作,当代码为 运行,如果引用为 "weak",它将静默失败而不会引起任何其他问题如果代码写对了)

另一方面,当一个变量是无主的时候,你基本上是在说这个变量将总是引用一些东西。与 weak 不同的是,如果你调用它但什么也没有,它就会崩溃。

你通常不想使用 unowned。 (我还没有遇到任何我必须这样做的情况)。另一方面,"weak self"变量在编写块时很常见。

这个问题你可以看到很好的解释:

Shall we always use [unowned self] inside closure in Swift

编辑:实际上,检查投票最多的第一和第二答案。他们对何时使用 unowned 及其工作原理提供了明确的解释。第二个还有图!