ARC,块和保留周期 [英] ARC, Blocks and Retain Cycles

查看:102
本文介绍了ARC,块和保留周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ARC处理面向4.0和5.0的iOS项目。

Working on an iOS project that targets 4.0 and 5.0, using ARC.

遇到与块,ARC和从块外引用对象相关的问题。以下是一些代码:

Running into an issue related to blocks, ARC and referencing an object from outside the block. Here's some code:

 __block AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
   [operation setCompletionBlock:^ {
       if ([operation isCancelled]) {
           return;
       }

... do stuff ...

operation = nil;
}];

在这种情况下,编译器发出一个警告,即在块中使用'operation'将导致保留周期。在ARC下,__block现在保留变量。

In this case, the compiler gives a warning that using 'operation' in the block is going to lead to a retain cycle. Under ARC, __block now retains the variable.

如果我添加__unsafe_unretained,编译器会立即释放该对象,所以显然不起作用。

If I add __unsafe_unretained, the compiler releases the object immediately, so obviously that won't work.

我的目标是4.0,所以我不能使用__weak。

I'm targeting 4.0 so I can't use __weak.

我尝试过这样的事情:

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
__block __unsafe_unretained AFHTTPRequestOperation *weakOperation = operation;

但是当weakOperation不是nil时,在块内部没有填充任何属性。

but while weakOperation isn't nil, none of it's properties are populated when inside the block.

鉴于上面列出的项目限制,处理这种情况的最佳方法是什么?

What's the best way to handle this situation given the project constraints listed above?

推荐答案

假设进度保证,保留周期可能正是您想要的。你明确地在块的末尾打破了保留周期,所以它不是一个永久的保留周期:当块被调用时,周期被打破。

Assuming progress guarantees, a retain cycle might be exactly what you want. You explicitly break the retain cycle at the end of the block, so it's not a permanent retain cycle: when the block is called, the cycle is broken.

如果你有保持操作的其他东西,你可以将引用存储到 __弱 __ unsafe_unretained 变量中然后使用在你的街区内。除非由于某种原因需要在块中更改变量的绑定,否则不需要 __ block - 限制变量;因为你没有剩余的保留周期,所以你不需要为弱变量分配任何东西。

If you have something else keeping the operation around, though, you can store a reference into either a __weak or __unsafe_unretained variable and then use that from within your block. There's no need to __block-qualify the variable unless you for some reason need to change the variable's binding during the block; since you don't have a retain cycle to break any more, you shouldn't need to assign anything to the weak variable.

这篇关于ARC,块和保留周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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