何时调用dealloc方法? [英] when is the dealloc method called?

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

问题描述

何时调用 dealloc 方法?我发现(在很多例子中)很多NS变量都是在它实例化的方法中发布的,但是当合成一个组件时,它们将释放放在dealloc方法中。

When exactly is the dealloc method called? I've found that (in a lot of examples) much of the NS variables are released in the method it's instantiated in, but when synthesizing a component they place the release in the dealloc method.

推荐答案

Apple参考文档明确说明
到接收者的后续消息可能会生成错误,指示消息是发送到解除分配的对象(如果尚未重新使用已释放的内存)。

The Apple reference document clearly states Subsequent messages to the receiver may generate an error indicating that a message was sent to a deallocated object (provided the deallocated memory hasn’t been reused yet).

您永远不会直接发送dealloc消息。相反,通过释放NSObject协议方法间接调用对象的dealloc方法(如果释放消息导致接收者的保留计数变为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版本,以允许释放对象消耗的任何额外内存 - 例如为解除分配的对象拥有的数据或对象实例变量动态分配存储。在执行特定于类的释放后,子类方法应该通过消息将dealloc的超类版本合并到super:

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
消息,因为进程的内存在退出时自动清除 - 只需允许操作系统清理它就更有效
资源比调用所有内存
管理方法。由于这个原因和其他原因,你不应该在
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

另一个SO问题 iPhone - 什么时候是一个名为的控制器的dealloc?

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

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