2

一部のブロックで弱い自己が必要な理由がわかりませんが、他のブロックは正常に機能しているようです。

Notificationブロックで自分自身への弱い参照がない場合、deallocは解放されません。ただし、2番目の場合は完全に正常に機能します。

//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];
}];
4

1 に答える 1

3

これは、1つの参照が時間の経過とともに(たとえば、完了ハンドラーが呼び出されたときに)なくなると、ブロックが解放されるためです。この場合、自己への参照が解放されるため、保持サイクルはありません。

ただし、NSNotificationの例では、ブロック参照はNSNotificationをリッスンしているため、(手動で削除しない限り)常に保持する必要があります。この場合、selfを参照すると保持サイクルが発生し、クラスが保持されなくなります。

于 2013-03-13T14:01:15.220 に答える