当我在 View Controller 的 -viewDidLoad:
方法中为 NSNotificationCenter
使用 -addObserverForName: object: queue: usingBlock:
时, -dealloc
方法最终未被调用。
(当我删除 -addObserverForName: object: queue: usingBlock:
时,再次调用 -dealloc
。)
使用-addObserver: selector: name: object:
好像没有这个问题。我究竟做错了什么? (我的项目正在使用 ARC。)
下面是我的实现示例,以防我在这里做错了什么:
[[NSNotificationCenter defaultCenter] addObserverForName:@"Update result"
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
updateResult = YES;
}];
在此先感谢您的帮助。
我尝试添加以下内容(无济于事):
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
if ([self isMovingFromParentViewController]) {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
}
最佳答案
updateResult
是一个实例变量,它防止对象被释放,因为它被该 block 保留。
换句话说,你有一个保留周期。对象保留 block , block 保留对象。
您将需要创建对该实例及其变量的弱引用或 unsafe_unretained 引用以失去该关系。
在通知 block 之前添加以下内容:
__unsafe_unretained YouObjectClass *weakSelf = self;
或者(如果您使用的是 iOS5 及更高版本)
__weak YouObjectClass *weakSelf = self;
然后,在该 block 中,通过新的弱引用引用该对象:
[[NSNotificationCenter defaultCenter] addObserverForName:@"Update result"
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
weakSelf.updateResult = YES;
}];
请注意,循环保留本身并不是一件坏事。有时你真的希望它们发生。但在某些情况下,您可以确定循环会在特定时间后被打破(例如动画 block )。一旦 block 已执行并从堆栈中删除,循环就会中断。
关于iphone - 在 ARC 中使用 NSNotificationCenter 代码块方法时,未调用 View Controller dealloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12699118/