One minor question: why is Xcode complaining that listing 1
would lead to a retain cycle, while in listing 2
it does not? In both cases _clients
is an int
instance variable. In listing 2
it is assigned 0
in the init
method.
Background info: I would like to execute the loop in the block, as long as at least one client is requesting updates from the iPhone accelerometer, which I am publishing to a redis channel. If there are no more clients left, the loop would quit and stop publishing accelerometer data.
Listing 2
comes from a small test app I wrote to verify that my idea works. Listing 1
is implemented in the real project.
Listing 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;
}
Listing 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);
}
});
}