ARC:Dealloc不被称为

问题描述:

我不明白为什么我需要在某些块中有一个弱自我,而其他人似乎工作正常。ARC:Dealloc不被称为

如果我对通知块没有弱自我引用,dealloc将不会被释放。尽管如此,它仍然可以很好地工作。

//When using this, dealloc is NOT being called 
[[NSNotificationCenter defaultCenter] addObserverForName:PROD_DONE object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) { 
    [self hideAds]; 
}]; 

//When using this, dealloc IS being called 
[_match endMatchInTurnWithMatchData:_match.matchData completionHandler:^(NSError *error) { 
    [self hideAds]; 
}]; 

如果我创建一个弱裁判的自我,它的工作原理:

__weak GameViewController *weakSelf = self; 
[[NSNotificationCenter defaultCenter] addObserverForName:PROD_DONE object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) { 
    [weakSelf hideAds]; 
}]; 
+1

在您的第一个代码示例中如何定义weakSelf? – 2013-03-13 14:01:42

这是因为一个引用消失一段时间(例如 - 当完成处理程序被调用),该块释放。在这种情况下,没有保留周期,因为对自我的引用将被释放。

但是,对于NSNotification示例,块引用必须始终保留(除非手动删除它),因为它仍在侦听NSNotification。在这种情况下,对自身的引用会导致保留周期,导致不保留该类。

+0

所以他可能在第一个代码示例中表示“self”,而不是“weakSelf”。 – 2013-03-13 14:05:39

+0

是啊,自我..感谢您的帮助 – BlackMouse 2013-03-13 14:08:25