Fix warning “Capturing [an object] strongly in thi

2019-01-03 12:15发布

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.

7条回答
Emotional °昔
2楼-- · 2019-01-03 13:01

When I try the solution provided by Guillaume, everything is fine in Debug mode but it crashs in Release mode.

Note that don't use __weak but __unsafe_unretained because my target is iOS 4.3.

My code crashs when setCompletionBlock: is called on object "request" : request was deallocated ...

So, this solution works both in Debug and Release modes :

// 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];        
}];
查看更多
登录 后发表回答