iOS阻止和对自我的强/弱引用 [英] iOS blocks and strong/weak references to self
问题描述
我有一个关于iOS中对self的强引用和弱引用的问题。我知道在块内引用self的正确方法是在块外创建一个弱引用,然后在块内强引用该弱引用,如下所示:
I have a question about strong and weak references to self in blocks in iOS. I know the proper way to refer to self inside a block is to create a weak reference outside the block, and then a strong reference to that weak reference inside the block, like this:
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^ {
typeof(self) strongSelf = weakSelf;
NSLog(@"%@", strongSelf.someProperty);
});
但是,如果你有嵌套块怎么办?一组参考文献足够吗?或者您是否需要为每个区块设置新组?例如,以下哪项是正确的?
However, what happens if you have nested blocks? Is the one set of references enough? Or do you need a new set for each block? For example, which of the following is correct?
这:
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^ {
typeof(self) strongSelf = weakSelf;
NSLog(@"%@", strongSelf.someProperty);
dispatch_async(dispatch_get_main_queue(), ^ {
strongSelf.view.frame = CGRectZero;
});
});
或者这个:
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^ {
typeof(self) strongSelf = weakSelf;
NSLog(@"%@", strongSelf.someProperty);
__weak typeof(strongSelf) weakSelf1 = strongSelf;
dispatch_async(dispatch_get_main_queue(), ^ {
typeof(strongSelf) strongSelf1 = weakSelf1;
strongSelf1.view.frame = CGRectZero;
});
});
非常感谢任何信息或解释!
Any information or explanation is much appreciated!
推荐答案
您不需要制作两组弱引用。你想要用块来避免的是一个保留周期 - 两个对象让对方不必要地活着。
You don’t need to make two sets of weak references. What you want to avoid with blocks is a retain cycle—two objects keeping each other alive unnecessarily.
如果我有一个具有这个属性的对象:
If I have an object with this property:
@property (strong) void(^completionBlock)(void);
我有这个方法:
- (void)doSomething
{
self.completionBlock = ^{
[self cleanUp];
};
[self doLongRunningTask];
}
当我将其存储在<$ c $中时,该块将保持活动状态c> completionBlock 属性。但是因为它在块中引用了 self
,所以该块将保持 self
alive直到它消失 - 但这会赢得'之所以会发生,因为它们都是相互引用的。
the block will be kept alive when I store it in the completionBlock
property. But since it references self
inside the block, the block will keep self
alive until it goes away—but this won’t happen since they’re both referencing each other.
在这种方法中:
- (void)doSomething
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self cleanUp];
}];
[self doLongRunningTask];
}
您不需要对自
。该块将保持 self
alive,因为它从内部引用 self
,但由于我们所做的只是处理阻止 [NSOperationQueue mainQueue]
, self
不会阻止该块活动。
you don’t need to make a weak reference to self
. The block will keep self
alive, since it references self
from within, but since all we’re doing is handing the block off to [NSOperationQueue mainQueue]
, self
isn’t keeping the block alive.
希望这会有所帮助。
这篇关于iOS阻止和对自我的强/弱引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!