在启用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
的使用。
发布于 2014-07-11 17:12:24
它是由于将自我保留在方块中而造成的。block将从self访问,self在Block中引用。这将创建一个保留周期。
尝试通过创建self
的弱引用来解决此问题
__weak typeof(self) weakSelf = self;
operationManager = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
[operationManager setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
[weakSelf requestFinishWithSucessResponseObject:responseObject withAFHTTPRequestOperation:operation andRequestType:eRequestType];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[weakSelf requestFinishWithFailureResponseObject:error withAFHTTPRequestOperation:operation andRequestType:eRequestType];
}];
[operationManager start];
发布于 2014-11-27 04:58:54
有时候xcode编译器在标识保留周期时会出现问题,所以如果你确定你没有保留completionBlock,你可以像这样放一个编译器标志:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-retain-cycles"
#pragma clang diagnostic ignored "-Wgnu"
-(void)someMethod {
}
发布于 2012-01-17 02:25:29
当我尝试Guillaume提供的解决方案时,在Debug模式下一切正常,但在Release模式下崩溃。
请注意,不要使用__weak而要使用__unsafe_unretained,因为我的目标是iOS 4.3。
当在对象" request“上调用setCompletionBlock:时,我的代码崩溃了:request被释放...
因此,此解决方案在调试和发布模式下都有效:
// Avoiding retain cycle :
// - ASIHttpRequest object is a strong property (crashs if local variable)
// - use of an __unsafe_unretained pointer towards self inside block code
self.request = [ASIHttpRequest initWithURL:...
__unsafe_unretained DataModel * dataModel = self;
[self.request setCompletionBlock:^
{
[dataModel processResponseWithData:dataModel.request.receivedData];
}];
https://stackoverflow.com/questions/7205128
复制相似问题