iphone - ARC 是否在任何自定义 -dealloc 代码之前或之后在 -dealloc 中插入代码?

标签 iphone ios ipad memory-management automatic-ref-counting

对于 ARC,有时我仍然需要编写一个 -dealloc 方法来进行一些清理。在极少数情况下,我需要引用实例的属性才能正确进行清理。例如从 NSNotificationCenter 中注销给定的发送者对象,该对象由属性拥有和引用。

ARC 是在我自己的代码之后的末尾插入它的属性释放代码,还是在 -dealloc 的开头,在我自己的代码之前插入它?

如果 ARC 将在任何自定义 -dealloc 代码之前插入代码,那么这将非常危险,因为如果需要,您将无法再访问属性。

这个问题是关于 ARC 在合成的 -dealloc 中插入属性释放代码的位置,而不是关于是否实现 -dealloc。

最佳答案

我想,一切都在这里说:http://clang.llvm.org/docs/AutomaticReferenceCounting.html#misc.special_methods.dealloc

7.1.2. dealloc

A program is ill-formed if it contains a message send or @selector expression for the selector dealloc.

Rationale: there are no legitimate reasons to call dealloc directly.

A class may provide a method definition for an instance method named dealloc. This method will be called after the final release of the object but before it is deallocated or any of its instance variables are destroyed. The superclass's implementation of dealloc will be called automatically when the method returns.

Rationale: even though ARC destroys instance variables automatically, there are still legitimate reasons to write a dealloc method, such as freeing non-retainable resources. Failing to call [super dealloc] in such a method is nearly always a bug. Sometimes, the object is simply trying to prevent itself from being destroyed, but dealloc is really far too late for the object to be raising such objections. Somewhat more legitimately, an object may have been pool-allocated and should not be deallocated with free; for now, this can only be supported with a dealloc implementation outside of ARC. Such an implementation must be very careful to do all the other work that NSObject's dealloc would, which is outside the scope of this document to describe.

关于iphone - ARC 是否在任何自定义 -dealloc 代码之前或之后在 -dealloc 中插入代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8964828/

相关文章:

iphone - 使用核心数据撤消管理

iphone - 使用 addOperationWithBlock 将 block 添加到队列并使用完成 block

iphone - 遍历数组并从 Core-Data 获取数据

iphone - 使用 drawRect 重绘

iphone - 点击获取 UILabel 标签

ios - (iOS Swift) 从 Core Data 获取记录返回 fatal error 或 nil

iphone - ios将网页保存为pdf

ios - xcode/ios : HIG: Is it better practice to have cancel and done or just back (with automatic save)

ios - LinkedIn URL方案可在iPad中打开公司资料

iphone - 在 xcode 的 Storyboard 中添加和控制 View Controller