ios - ARC 及其工作原理。

标签 ios swift memory-management automatic-ref-counting

我刚刚学习了有关 ARC 的教程并获得了此代码。

下面是 ViewController 类,下面是 Vehicle 类。

我从中得到的是,ARC 本质上是跟踪一个实例化的类并为其分配一 block 内存。当创建实例的“强”引用时,arc 会增加对实例的引用数量的增量。一旦所有这些都设置为 nil,ARC 就会从内存中释放实例。讲师还说了一些类似的话,一旦所有引用都没有被使用,它就会从内存中释放。我不太明白它们没有被“使用”的部分,所以我决定添加一个按钮,它显示另一个没有代码的空白 View Controller 。我想如果我导航到下一个 View Controller ,deinit 将被调用,因为 View Controller 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")

}}

最佳答案

  1. “使用过”的术语令人困惑/误导(或者充其量是不精确的)。使用 ARC,对象将不会被释放,直到没有剩余的强引用,简单明了。如果您 nil 所有这些强引用,或者那些强引用超出范围,则对象将被释放。

    顺便说一句,请注意 scheduledTimerWithTimeInterval 建立了自己对其目标的强引用。您必须使计时器无效才能解析该强引用。

  2. ARC 仅适用于引用类型(即 class 实例)。它根本不适用于值类型(例如数字类型或 struct 类型)。

    因此,考虑

    var number = 2 
    var othernumber = number
    

    othernumber 不引用 number。它制作了一份副本。它是一个新对象,其值恰好与 number 的值相同。有关区分 Swift 值类型和引用类型的讨论,请参阅 WWDC 2015 Building Better Apps with Value Types . (顺便说一句,复杂值类型的幕后内存管理实际上比简单值类型更复杂,但它在这个对话中并不是很相关。但是如果你在视频中会详细讨论它有兴趣。)

关于ios - ARC 及其工作原理。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39156406/

相关文章:

c# - 释放变量占用的内存

c++ - 如何在内存中保留 C++ 对象?

ios - 使用 Xcode 提交到 App Store

ios - UIImagePickerController 和 UINavigationController 完成后导航?

ios - 如果 NSDictionary 具有键的整数,我如何将 NSDictionary 转换为快速字典

objective-c - 如何将 Chartboost IOS SDK 与 Swift 集成

Swift - 在讲话时改变音量

Android - 从低内存状态中恢复

ios - 排序字符串包含数字,NSMutableArray 与字典

ios - 在 iOS 中获取 Facebook 好友列表