在启用 ARC 的代码中,使用基于 block 的 API 时如何修复有关潜在保留周期的警告?
警告:
在此 block 中强烈捕获“请求”可能会导致保留周期
由这段代码生成:
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:...
[request setCompletionBlock:^{
NSDictionary *jsonDictionary = [[CJSONDeserializer deserializer] deserialize:request.rawResponseData error:nil];
// ...
}];
警告与 block 内对象request
的使用有关。
最佳答案
回复我自己:
我对文档的理解是,使用关键字 block
并在 block 内使用它后将变量设置为 nil 应该没问题,但它仍然显示警告。
__block ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:...
[request setCompletionBlock:^{
NSDictionary *jsonDictionary = [[CJSONDeserializer deserializer] deserialize:request.responseData error:nil];
request = nil;
// ....
}];
更新:让它使用关键字“_weak”而不是“_block”,并使用临时变量:
ASIHTTPRequest *_request = [[ASIHTTPRequest alloc] initWithURL:...
__weak ASIHTTPRequest *request = _request;
[request setCompletionBlock:^{
NSDictionary *jsonDictionary = [[CJSONDeserializer deserializer] deserialize:request.responseData error:nil];
// ...
}];
如果您还想以 iOS 4 为目标,请使用 __unsafe_unretained
而不是 __weak
。相同的行为,但当对象被销毁时,指针保持悬空状态,而不是自动设置为 nil。
关于cocoa-touch - 修复启用 ARC 的代码中的警告 "Capturing [an object] strongly in this block is likely to lead to a retain cycle",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7205128/