是否有必要使用弱引用自我总是在块内?
我使用自我内部块,我通过一些苹果的文档,但仍然找不到正确的答案困惑。
I am getting confused with use of self inside blocks, I go through some of Apple's documents but still cannot find the right answer.
有些人总是说使用弱
示例1:
self.handler = ^(id response, NSError *error)
{
self.newresponse = response; //use weak self here
};
示例2:
;
__weak myViewController *weakSelf = self;
[UIView animateWithDuration:interval delay:0.0 options:curve animations:^
{
[weakSelf.view.superview setTransform:CGAffineTransformMakeTranslation(0, -106)];
//in above is it use of weak is neassary
}
completion:^(BOOL finished)
{
}];
没有弱自我;
__weak myViewController *weakSelf = self;
[UIView animateWithDuration:interval delay:0.0 options:curve animations:^
{
[myViewController.view.superview setTransform:CGAffineTransformMakeTranslation(0, -106)];
}
completion:^(BOOL finished)
{
}];
在上面的例子中,
**我使用ARC
In the above samples, which are correct…? **I am using ARC
您应该只使用弱引用 self
,如果 self
将保留对块的引用。
You should only use a weak reference to self
, if self
will hold on to a reference of the block.
例如,您不是在 self
中保留对块的引用,您只使用与 UIView animateWithDuration:
,因此没有必要使用 __ weak myViewController * weakSelf = self;
In your example, you are not keeping a reference to your block in self
, you are only using blocks inline with the UIView animateWithDuration:
, and as such there is no need to use __weak myViewController *weakSelf = self;
案件?因为一个块将保留对它使用的任何变量的强引用。这包括 self
。现在如果类实例本身保持对块的强引用,并且块保持对类实例的强引用,那么您将有一个保留周期,这将导致内存泄漏。
Why is this the case? Because a block will retain strong references to any variables it uses from the class using the block. This includes self
. Now if the class instance itself keeps a strong reference to the block, and the block keeps a strong reference to the class instance, you have a retain cycle, which will cause memory leaks.