修复警告“在该块中强烈捕获[对象]可能导致保留周期”在启用ARC的代码中 [英] Fix warning "Capturing [an object] strongly in this block is likely to lead to a retain cycle" in ARC-enabled code

查看:149
本文介绍了修复警告“在该块中强烈捕获[对象]可能导致保留周期”在启用ARC的代码中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



警告:

在此块中强烈捕获请求可能导致此代码段生成的保留周期



代码:

  ASIHTTPRequest * request = [[ASIHTTPRequest alloc] initWithURL:... 

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

警告与对象的使用请求


= 我对文档的理解说,在块中使用关键字 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。


In ARC enabled code, how to fix a warning about a potential retain cycle, when using a block-based API?

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

produced by this snippet of code:

ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:...

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

Warning is linked to the use of the object request inside the block.

解决方案

Replying to myself:

My understanding of the documentation says that using keyword block and setting the variable to nil after using it inside the block should be ok, but it still shows the warning.

__block ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:...

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

    }];

Update: got it to work with the keyword '_weak' instead of '_block', and using a temporary variable:

ASIHTTPRequest *_request = [[ASIHTTPRequest alloc] initWithURL:...
__weak ASIHTTPRequest *request = _request;

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

If you want to also target iOS 4, use __unsafe_unretained instead of __weak. Same behavior, but the pointer stays dangling instead of being automatically set to nil when the object is destroyed.

这篇关于修复警告“在该块中强烈捕获[对象]可能导致保留周期”在启用ARC的代码中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆