![](/img/trans.png)
[英]Coredata memory leak: Deinit does not get called.. causing memory leak
[英]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,这导致两个对象都被释放。
让我困惑的事情:
在我的实际代码/我遵循的教程中,我从未在我的班级中看到“deinit”,并且我从未将 nil 分配给实例,因此该对象永远不会被释放,并且它会像胖子一样占用我的内存空间? 我应该在我的代码中写 deinit 吗? 因为我认为如果空间有限,它会充满数据对象,最终我的应用程序会崩溃
据说:
自动引用计数以指示对象是否仍在使用或不再需要
不再需要? 这是什么意思?
只是为了从你的例子中澄清:
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
回答您的问题:
如果您永远不需要将nil
分配给bob
(根据上下文可能没有意义),您应该将bob
的类型分配为Human
,而不是Human?
. 这意味着 bob 永远不会也永远不会为零,并且使您的代码更易于推理。 这并不意味着位于bob
的Human
对象永远不会从内存中消失。 例如,如果bob
在某个视图控制器中,该控制器在某个时候被释放(如果用户导航离开该 VC 或应用程序已关闭),那么bob
当然也会被系统释放。
从您的代码的访问角度来看,“不再需要”意味着“需要”。 如果bob
设置为 nil,您为什么需要再次访问有关他的信息? 你没有,所以位于bob
的对象的引用计数减少到 0,不再需要,并被释放。
我希望我能为你澄清一些事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.