首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >修复启用ARC的代码中“在此块中强烈捕获[对象]可能导致保留循环”的警告

修复启用ARC的代码中“在此块中强烈捕获[对象]可能导致保留循环”的警告
EN

Stack Overflow用户
提问于 2011-08-26 21:10:25
回答 5查看 47.5K关注 0票数 142

在启用ARC的代码中,当使用基于块的API时,如何修复有关潜在保留周期的警告?

警告:

Capturing 'request' strongly in this block is likely to lead to a retain cycle

由这段代码产生:

代码语言:javascript
复制
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:...

[request setCompletionBlock:^{
    NSDictionary *jsonDictionary = [[CJSONDeserializer deserializer] deserialize:request.rawResponseData error:nil];
    // ...
    }];

警告链接到块内对象request的使用。

EN

回答 5

Stack Overflow用户

发布于 2014-07-11 17:12:24

它是由于将自我保留在方块中而造成的。block将从self访问,self在Block中引用。这将创建一个保留周期。

尝试通过创建self的弱引用来解决此问题

代码语言:javascript
复制
__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];
票数 14
EN

Stack Overflow用户

发布于 2014-11-27 04:58:54

有时候xcode编译器在标识保留周期时会出现问题,所以如果你确定你没有保留completionBlock,你可以像这样放一个编译器标志:

代码语言:javascript
复制
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-retain-cycles"
#pragma clang diagnostic ignored "-Wgnu"

-(void)someMethod {
}
票数 6
EN

Stack Overflow用户

发布于 2012-01-17 02:25:29

当我尝试Guillaume提供的解决方案时,在Debug模式下一切正常,但在Release模式下崩溃。

请注意,不要使用__weak而要使用__unsafe_unretained,因为我的目标是iOS 4.3。

当在对象" request“上调用setCompletionBlock:时,我的代码崩溃了:request被释放...

因此,此解决方案在调试和发布模式下都有效:

代码语言:javascript
复制
// 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];        
}];
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7205128

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档