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

在启用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块内对象的使用有关。


皈依舞
浏览 660回答 3
3回答

陪伴而非守候

回复自己:我对文档的理解是,在模块中使用关键字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。

翻翻过去那场雪

发生此问题的原因是,您正在为要分配的请求分配一个对请求具有强引用的块。该块将自动保留请求,因此原始请求不会因为周期而取消分配。说得通?这很奇怪,因为您正在使用__block标记请求对象,以便它可以引用自身。您可以通过在其旁边创建一个弱引用来解决此问题。ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:...];__weak ASIHTTPRequest *wrequest = request;[request setCompletionBlock:^{    NSDictionary *jsonDictionary = [[CJSONDeserializer deserializer] deserialize:wrequest.rawResponseData error:nil];    // ...    }];

慕斯王

这是由于将自身保留在块中引起的。块将从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];
打开App,查看更多内容
随时随地看视频慕课网APP