ios - 在 Swift 中,我应该在完成后将可选实例变量设置为 nil 吗?

标签 ios swift memory memory-management option-type

我在我的一个应用程序中使用了大量的音频、视频和图像,并且似乎有轻微的内存问题,我想知道释放内存的最佳方法是什么。

我使用了很多这样的可选变量:

var myImageView: UIImageView?

我想知道是否将这些设置为 nil 是最佳做法,一旦您知道不再需要它来释放内存,如下所示:

myImageView = nil

似乎将它设置为 nil 会删除最后一个强引用并导致它被释放,但如果可能的话,我也不想在我的代码中到处乱扔 XXXX = nil。

我还考虑为使用该变量的类创建一个 deinit 方法,并在其中执行如下操作:

deinit {
    myImageView = nil
}

唯一的问题是我正在使用的实例在再次使用之前实际上并没有被销毁。但是通常当一个实例被销毁时,它的所有可选项也应该被释放,对吧?

最佳答案

来自 Apple 的 documentation关于自动引用计数 (ARC),他们说:

Swift uses Automatic Reference Counting (ARC) to track and manage your app’s memory usage. In most cases, this means that memory management “just works” in Swift, and you do not need to think about memory management yourself. ARC automatically frees up the memory used by class instances when those instances are no longer needed.

你觉得下面的部分很有趣

However, in a few cases ARC requires more information about the relationships between parts of your code in order to manage memory for you.

你还没有发布任何代码,所以我不知道你是否有弱引用、无主引用、闭包的强引用循环等。

例如,如果您有一个强大的闭包引用周期,如上面的文档链接中所述:

Swift provides two ways to resolve strong reference cycles when you work with properties of class type: weak references and unowned references.

我认为阅读文档会对您有所帮助,因为它可以让您清楚地了解 ARC 在 Swift 中的工作原理。

关于ios - 在 Swift 中,我应该在完成后将可选实例变量设置为 nil 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35463400/

相关文章:

java - 来自配置文件或 .java 的巨大数组

java - 实例方法是按对象还是按类加载到内存中?

ios - UIView 中需要 uitableview 分组背景吗?

ios - Xcode 12 中的 `Hide or Show debug area` 图标在哪里?

ios - ios开发之ping和arp

ios - 在 Objective C 代码中使用从 Objective C 库代码继承的 Swift 类

ios - 如何解码对象数组并从用户默认值中检索它?

c - 如何以编程方式在 Linux 中获取物理内存地址范围

ios - 滑动动画和功能

ios - 将快速闭包传递给以 block 作为参数的 Objective-C 函数