谁在 Objective C 中调用 dealloc 方法? [英] Who calls the dealloc method and when in Objective C?

查看:76
本文介绍了谁在 Objective C 中调用 dealloc 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在 Objective C 中创建自定义类时,dealloc 方法何时以及如何调用?这是我必须在课堂上以某种方式实现的东西吗?

When a custom class is created in Objective C, when and how is the dealloc method called? Is it something that I have to implement somehow in my class?

推荐答案

您从不直接发送 dealloc 消息.相反,对象的 dealloc 方法是通过释放 NSObject 协议方法间接调用的(如果释放消息导致接收者的保留计数变为 0).有关使用这些方法的更多详细信息,请参阅内存管理编程指南.

You never send a dealloc message directly. Instead, an object’s dealloc method is invoked indirectly through the release NSObject protocol method (if the release message results in the receiver's retain count becoming 0). See Memory Management Programming Guide for more details on the use of these methods.

子类必须实现自己的 dealloc 版本,以允许释放对象消耗的任何额外内存——例如动态分配的存储空间,用于数据或被释放对象拥有的对象实例变量.在执行特定于类的解除分配后,子类方法应通过向 super 发送消息合并超类版本的 dealloc:

Subclasses must implement their own versions of dealloc to allow the release of any additional memory consumed by the object—such as dynamically allocated storage for data or object instance variables owned by the deallocated object. After performing the class-specific deallocation, the subclass method should incorporate superclass versions of dealloc through a message to super:

重要:请注意,当应用程序终止时,可能不会向对象发送 dealloc消息,因为进程的内存会在退出时自动清除——它更有效率只是为了让操作系统清理资源而不是调用所有内存管理方法.由于这个原因和其他原因,你不应该管理稀缺资源解除分配

Important: Note that when an application terminates, objects may not be sent a dealloc message since the process’s memory is automatically cleared on exit—it is more efficient simply to allow the operating system to clean up resources than to invoke all the memory management methods. For this and other reasons, you should not manage scarce resources in dealloc

 - (void)release
 {
   _retainCount--;
   if (_retainCount == 0) {
       [self dealloc];
    }
  }

这篇关于谁在 Objective C 中调用 dealloc 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆