有一个小问题:为什么Xcode会抱怨
Listing 1
会导致保留环,而在Listing 2
中却没有?在两种情况下,_clients
都是一个int
实例变量。在Listing 2
中,它在init
方法中被赋值为0
。
背景信息:我想在块中执行循环,只要至少有一个客户端请求从iPhone加速计更新,我就将其发布到redis频道。如果没有更多的客户端,循环将退出并停止发布加速计数据。
Listing 2
来自我编写的一个小测试应用程序,以验证我的想法是否可行。 Listing 1
在真实项目中实现。
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;
}
清单 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);
}
});
}
id
作为weakself
,但你应该使用适当的类型。如果你使用 Objective-C++,你可以将本地副本clients
声明为auto clients
,推断变量类型。 - fabrice truillot de chambrier