問題描述
使用 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;
}];
在這種情況下,編譯器會發(fā)出警告,在塊中使用操作"將導致保留循環(huán).在 ARC 下,__block 現(xiàn)在保留了變量.
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,但它的任何屬性都不會在塊內(nèi)填充.
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?
推薦答案
假設進度保證,保留周期可能正是您想要的.您在塊結束時顯式中斷保留循環(huán),因此它不是永久保留循環(huán):當調(diào)用塊時,循環(huán)被中斷.
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.
但是,如果您有其他東西保持操作,您可以將引用存儲到 __weak
或 __unsafe_unretained
變量中,然后在您的塊中使用它.除非您出于某種原因需要在塊期間更改變量的綁定,否則無需對變量進行 __block
限定;由于您不再需要中斷循環(huán),因此您不需要為弱變量分配任何內(nèi)容.
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、塊和保留周期的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!