挂钩的ARC dealloc [英] Hooking end of ARC dealloc
问题描述
给出以下简单实现:
@implementation RTUDeallocLogger
-(void)dealloc
{
NSLog(@"deallocated");
}
@end
我们在ARC下运行以下代码:
we run the following code under ARC:
@implementation RTURunner
{
NSArray* arr;
}
-(void)run{
arr = [NSArray
arrayWithObjects:[[RTUDeallocLogger alloc]init],
[[RTUDeallocLogger alloc]init],
[[RTUDeallocLogger alloc]init],
nil];
NSLog(@"nulling arr");
arr = NULL;
NSLog(@"finished nulling");
}
@end
我们得到以下日志输出:
we get the following log output:
nulling arr
finished nulling
deallocated
deallocated
deallocated
我想在所有释放完成后执行一个动作.这可能吗?
I'd like to perform an action after all the deallocations have finished. Is this possible?
这个问题的目的实际上是对ARC的机制有更多的了解,特别是ARC在什么时候触发了这些释放,以及在我删除引用时是否可以同步发生./em>
The aim of this question is really to understand a little more about the mechanics of ARC, in particular, at what point ARC triggers these deallocations, and whether or not this can ever happen synchronously when I drop references.
推荐答案
-dealloc始终是同步的,并且在删除最后一个强引用时发生.不过,对于您的代码,+ arrayWithObjects:很有可能(如果至少在-O0进行编译)会将数组放入自动释放池中,因此最后一个强引用在池耗尽时被删除,而不是在将变量设置为NULL时被删除. (您应该对ObjC对象使用nil,顺便说一句).
-dealloc is always synchronous, and occurs when the last strong reference is removed. In the case of your code though, +arrayWithObjects: is likely (if compiled at -O0 at least) putting the array in the autorelease pool, so the last strong reference is removed when the pool drains, not when you set the variable to NULL (you should use nil for ObjC objects, btw).
您可以通过使用alloc/init创建对象来避免将对象包含在自动释放池中,并且也许(实现细节,等等)可以通过启用优化进行编译来避免该对象.您还可以使用@autoreleasepool {}引入内部池并以此方式限制生存期.
You can likely avoid having the object in the autorelease pool by using alloc/init to create, and you may (implementation detail, bla bla) be able to avoid it by compiling with optimizations turned on. You can also use @autoreleasepool { } to introduce an inner pool and bound the lifetime that way.
这篇关于挂钩的ARC dealloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!