如果我是 Apple 的工程师,我可能会争辩说你的问题可能是你的设计。您几乎没有理由希望通过观察dealloc
而不是让dealloc
自己行动来有效地采取行动。
[一个巨大的编辑如下:弱属性不通过正常的属性机制,因此它们不符合 KVO,包括最初提议的内部隐式 KVO]
也就是说,您可以做的是通过对象关联将两个对象的生命周期绑定在一起,并使用后者的 dealloc 作为对前者的 dealloc 的调用。
所以,例如
#import <objc/runtime.h>
@interface DeallocNotifier;
- (id)initWithObject:(id)object target:(id)target action:(SEL)action;
@end
@implementation DeallocNotifier
- (id)initWithObject:(id)object target:(id)target action:(SEL)action
{
... blah ...
// we'll use a static int even though we'll never access by this key again
// to definitely ensure no potential collisions from lazy patterns
static int anyOldKeyWellNeverUseAgain;
objc_setAssociatedObject(object, &anyOldKeyWellNeverUseAgain, self, OBJC_ASSOCIATION_RETAIN);
... blah ...
}
- (void)dealloc
{
[_target performSelector:_action];
}
@end
-(void)run{
arr = ...
[[DeallocNotifier alloc]
initWithObject:arr target:self action:@selector(arrayDidDealloc)];
/* you may not even need *arr in this case; I'm unclear as
to why you have an instance variable for something you don't
want to keep, so I guess it'll depend on your code */
} // end of run
- (void)arrayDidDealloc
{
NSLog(@"array was deallocated");
}
我假设您能够将您感兴趣的所有对象的生命周期与单个容器的生命周期联系起来;否则您可以将通知程序与所有相关对象相关联。
你得到的时候阵列肯定已经消失了arrayDidDealloc
。