更新:从 iOS 9 和 OS X 10.11 开始,NSNotificationCenter 观察者在被释放时不再需要取消注册。(来源:在 iOS 9 中取消注册 NSNotificationCenter 观察者)
(旧答案:)即使使用 ARC,您也必须在释放通知中心时从通知中心删除观察者。您的程序没有崩溃可能是纯粹的机会。
下面的程序演示了这一点。我已经激活了“启用僵尸对象”选项。
@interface MyObject : NSObject
@end
@implementation MyObject
-(id)init
{
self = [super init];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notify:) name:@"test" object:nil];
}
return self;
}
- (void)dealloc
{
NSLog(@"dealloc");
//[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)notify:(NSNotification *)notification
{
NSLog(@"notify");
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
MyObject *o = [[MyObject alloc] init];
[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil];
o = nil; // This causes the object to be deallocated
// ... and this will crash
[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil];
}
return 0;
}
输出:
notifytest[593:303] notify
notifytest[593:303] dealloc
notifytest[593:303] *** -[MyObject notify:]: message sent to deallocated instance 0x100114290