ちょっとした質問: なぜ Xcode はlisting 1
保持サイクルにつながると不平を言っているのに、listing 2
そうではないのでしょうか? どちらの場合も_clients
インスタンスint
変数です。メソッドでlisting 2
割り当てられ0
ますinit
。
背景情報: 少なくとも 1 つのクライアントが iPhone 加速度計からの更新を要求している限り、ブロック内のループを実行したいと思います。これを redis チャネルに公開しています。クライアントが残っていない場合、ループは終了し、加速度計データの公開を停止します。
Listing 2
私のアイデアが機能することを確認するために書いた小さなテストアプリから来ています。Listing 1
実際のプロジェクトで実装されます。
リスト 1
- (id)init {
self = [super init];
if (self) {
_clients = 0;
/**
* The callback being executed
*/
_callback = ^ {
while (_clients > 0) { // Capturing 'self' strongly in this block is likely to lead to a retain cycle
NSLog(@"Publish accelerometer data to redis (connected clients: %d)", _clients);
}
};
}
return self;
}
リスト 2
- (void)touchedConnectButton:(id)sender {
_clients += 1;
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(concurrentQueue, ^() {
while(_clients > 0) {
NSLog(@"Connected clients: %d", _clients);
}
});
}