在启用 ARC 的代码中,如何在使用基于块的 API 时修复有关潜在保留周期的警告?
警告:Capturing 'request' strongly in this block is likely to lead to a retain cycle
由这段代码生成:
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:...
[request setCompletionBlock:^{
NSDictionary *jsonDictionary = [[CJSONDeserializer deserializer] deserialize:request.rawResponseData error:nil];
// ...
}];
警告与块内对象
request
的使用有关。 最佳答案
回复我自己:
我对文档的理解表明,使用关键字 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/