cocoa-touch - 修复启用 ARC 的代码中的警告 "Capturing [an object] strongly in this block is likely to lead to a retain cycle"

标签 cocoa-touch cocoa asihttprequest automatic-ref-counting retain

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

警告:
在此 block 中强烈捕获“请求”可能会导致保留周期

由这段代码生成:

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

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

警告与 block 内对象request的使用有关。

最佳答案

回复我自己:

我对文档的理解是,使用关键字 block 并在 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/

相关文章:

iphone - 将 NSOperation 添加到启动异步 ASIHTTPRequest 的 NSOperationQueue

ios - 使用 shareKit 在 Twitter 上分享图片。推文中可见缩短的 URL,而不是实际附加的图像

iphone - 对象泄露 : allocated object is not referenced later in this execution path and has a retain count of +1

macos - 当用户返回 NSViewController 时执行某些操作

cocoa - 如何在没有 Accessibility API 的情况下在 Mac OS 中获取另一个应用程序窗口的标题、位置和大小?

ios - 将userid存储在内存IOS

xcode - 核心数据和NSPredicate : Relationships

iphone - 通过 UIView 更改 MaskedLayer 的大小

multithreading - 我的 cocoa 应用程序记录了一些 "[Switching to process XXXX thread 0xXXXX]"

php - ASIHTTPRequest - 将 JSON 发布到 PHP