【发布时间】:2016-08-25 23:50:38
【问题描述】:
我刚刚学习了有关 ARC 的教程,并获得了此代码。
下面的 ViewController 类和下面的 Vehicle 类。
我从中得到的是,ARC 本质上是跟踪一个实例化的类并为它分配一块内存。当创建实例的“强”引用时,arc 会增加对实例的引用数量的增量。一旦所有这些都设置为 nil,ARC 就会从内存中释放实例。讲师还说了一些类似的话,一旦所有引用都没有被使用,它就会从内存中释放。我不太明白它们没有被“使用”的部分,所以我决定添加一个按钮,它显示另一个没有代码的空白视图控制器。我想如果我导航到下一个视图控制器,deinit 将作为视图控制器 1 中的引用被调用,现在没有被使用,因此从内存中释放。情况并非如此,并且 deinit 没有被调用。因此,我想知道,除非您将它们设置为 nil,否则引用会一直保留在内存中吗?
问题的第 2 部分:此外,当您回答这个问题时,我还有另一个问题,我还想知道 ARC 是否仅适用于类实例和对它的引用,因为我查阅了每篇文档或教程似乎只提到类实例。例如,如果我设置 var number = 2
var othernumber = number ,“数字”是否也存储在内存中,并且只有在所有对它的引用都为零时才被释放。如果也是这种情况,那么同样的问题也适用,将所有引用设置为 nil 是从内存中释放的唯一方法吗?很抱歉这个冗长的问题,但我对记忆概念很陌生。
import UIKit
class ViewController: UIViewController {
var ref1: Vehicle?
var reference2: Vehicle?
var ref3: Vehicle?
var timer: NSTimer!
var count = 0
override func viewDidLoad() {
super.viewDidLoad()
ref1 = Vehicle(kind: "Car")
reference2 = ref1
ref3 = ref1
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(tick), userInfo: nil, repeats: true)
}
func tick() {
count++
if count >= 3 {
ref3 = nil
reference2 = nil
}
if count == 5 {
ref1 = nil
}
}
}
class Vehicle {
let type: String
init(kind: String){
self.type = kind
print("\(type) is being initialized")
//when the class is instantiated, we get an initialization message. When class is deallocated, we get a deinit message. As in, all strong references are gone, we can deinitialize.
}
deinit {
//class vehicle not in memory anymore as all strong references to it have been destroyed. This will be tested with segue as well.
print("\(type) is being deinitialized")
}}
【问题讨论】:
标签: ios swift memory-management automatic-ref-counting