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

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

问题描述

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

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

警告:
在这个block中强烈捕获'request'很可能会导致retain cycle

由这段代码产生:

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

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

警告与块内对象request的使用有关.

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

推荐答案

回复自己:

我对文档的理解是使用关键字 block 并将变量设置为 nil 在块内使用后应该没问题,但它仍然显示警告.

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;
// ....

    }];

更新:让它使用关键字_weak"而不是_block",并使用临时变量:

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];
    // ...
    }];

如果您还想针对 iOS 4,请使用 __unsafe_unretained 而不是 __weak.行为相同,但指针保持悬空状态,而不是在对象销毁时自动设置为 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天全站免登陆