繁体   English   中英

与 Deinit 和内存泄漏混淆

[英]Confused with Deinit and Memory leak

我正在尝试了解 iOS 开发中的内存管理。 我读了这篇文章/教程: 让内存管理再次伟大

在该教程中,类中有一个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. 据说:

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

不再需要? 这是什么意思?

只是为了从你的例子中澄清:

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

回答您的问题:

  1. 如果您永远不需要将nil分配给bob (根据上下文可能没有意义),您应该将bob的类型分配为Human ,而不是Human? . 这意味着 bob 永远不会也永远不会为零,并且使您的代码更易于推理。 并不意味着位于bobHuman对象永远不会从内存中消失。 例如,如果bob在某个视图控制器中,该控制器在某个时候被释放(如果用户导航离开该 VC 或应用程序已关闭),那么bob当然也会被系统释放。

  2. 从您的代码的访问角度来看,“不再需要”意味着“需要”。 如果bob设置为 nil,您为什么需要再次访问有关他的信息? 你没有,所以位于bob的对象的引用计数减少到 0,不再需要,并被释放。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM