我们在课堂上观察通知 - [NSNotificationCenter addObserverForName:object:queue:usingBlock:]但是随着EXC_BAD_ACCESS随机崩溃。
@interface Test: NSObject {
id obs;
}
@end
@implementation Test
- (id)init {
self = [super init];
if (self) {
Test * __weak weakSelf = self;
self->obs = [[NSNotificationCenter defaultCenter] addObserverForName:Notification object:nil queue:nil usingBlock:^(NSNotification *note) {
Test *strongSelf = weakSelf;
if (!strongSelf) {
return;
}
[strongSelf handleNotification:note];
}];
}
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self->obs];
self->obs = nil;
}
@end
我们发现,有时当发布通知时,NSNotificationCenter已经获得观察者并准备调用该块通知但同时,该对象被解除分配,因此使用self-gt; obs,这使得它成为可能由于zombie self-> obs
而导致[NSNotification postNotification ...]方法崩溃是否有解决方法或修复此问题?
PS。这是ARC代码。