我们有一个用 -[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->obs,这使得它在 [NSNotification postNotification...] 方法,因为僵尸 self->obs
是否有任何解决方法或解决此问题的方法?
PS。这是 ARC 代码。