Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
526 views
in Technique[技术] by (71.8m points)

cocoa touch - Is it necessary to use weak references to self always inside blocks..?

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.

Some people always say use weak self inside blocks, but some say use weak self in blocks that are copied, not neassary to use always.

Sample 1:

self.handler = ^(id response, NSError *error)
{
    self.newresponse = response; //use weak self here
};  

Sample 2:

Using weak self;

__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)
{

}];

Without weak self;

__weak myViewController *weakSelf = self;

[UIView animateWithDuration:interval delay:0.0 options:curve animations:^
{
    [myViewController.view.superview setTransform:CGAffineTransformMakeTranslation(0, -106)];

}
completion:^(BOOL finished)
{

}];

In the above samples, which are correct…? **I am using ARC

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should only use a weak reference to self, if self will hold on to a reference of the block.

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;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...