【问题标题】:Confused with Deinit and Memory leak对 Deinit 和内存泄漏感到困惑
【发布时间】:2018-03-14 14:30:18
【问题描述】:

我正在尝试学习 iOS 开发中的内存管理。我看了这篇文章/教程:Make Memory Management Great Again

在那篇教程中,类中有一个deinit 方法,如下所示:

class Human {
  var passport: Passport?
  let name: String

  init(name: String) {
    self.name = name
  }

  deinit {
    print("I'm gone, friends")
  }
}

创建实例后,引用计数为 1,因为它是强引用。直到这一步,我明白了。

var bob: Human? = Human(name: "Bob Lee")

据说当我们创建一个实例时,它实际上会占用我们的 RAM 空间。

如果我们将 nil 分配给 'bob' 变量,deinit 将打印(“我走了,朋友们”),并且关系不再存在,因此引用计数变为 0,这将导致两个对象都被释放。

让我困惑的事情:

  1. 在我的实际代码/我遵循的教程中,我从来没有在我的课程中看到“deinit”,我从来没有将 nil 分配给实例,所以该对象永远不会被释放,它会占用我的内存空间像脂肪一样?我应该在我的代码中写 deinit 吗?因为我认为如果空间有限,它会被数据对象填充,最终我的应用程序会崩溃

  2. 据说:

自动引用计数以指示对象是否静止 正在使用或不再需要

不再需要?什么意思?

【问题讨论】:

标签: ios swift memory-management memory-leaks


【解决方案1】:

只是从你的例子中澄清一下:

var bob: Human? = Human(name: "Bob Lee")
// bob now has a reference count of 1
// the memory at the bob location is ready to access and/or modify
// this means bob is still alive and we can find out things about him

print(bob!.name) 
// prints "Bob Lee"

bob = nil
// deinit called, "I'm gone, friends"
// bob now has a reference count of 0, and ARC has released the object that was stored here
// we cannot find out anything about bob
// the memory at the location of bob is now released

print(bob!.name)
// Error: Unexpectedly found nil while unwrapping optional value

回答您的问题:

    1234563 .这意味着 bob 永远不会也永远不会是 nil,并使您的代码更容易推理。这并不意味着位于bobHuman 对象永远不会从内存中消失。例如,如果bob 位于某个视图控制器中,该视图控制器在某个时间点被释放(如果用户离开该 VC 或应用程序已关闭),bob 当然也会被系统释放。
  1. “不再需要”意味着从您的代码的访问角度来看“需要”。如果bob 设置为 nil,为什么您需要再次访问有关他的信息?你没有,所以位于bob 的对象的引用计数减少到 0,不再需要,并被释放。

我希望我能为你澄清一些事情。

【讨论】:

    猜你喜欢
    • 2011-10-02
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 2020-11-10
    • 2021-11-16
    • 2021-11-28
    • 2017-01-13
    • 1970-01-01
    相关资源
    最近更新 更多