Do we need to use __weak self inside UIAnimationBlocks in ARC?

点点圈 提交于 2019-12-17 17:40:55

问题


Do we need to use __weak self inside UIAnimation Blocks as given below? Whether it will create retain cycle issue if we are not specifying self as weak?

[UIView animateWithDuration:animationDuration 
                      delay:0 
                    options:UIViewAnimationCurveEaseInOut 
                 animations:^{
        [self doSomething];
    } completion:^(BOOL finished) {
        if (finished) {
            [self doSomething];
        }
    }];

I am also confused in the following scenario. Any thoughts on this? please share your comments.

[self.navController dismissViewControllerAnimated:animated 
                                       completion:^{
                                                      [self doSomething];
                                                  }];

Should we use weak self here?


回答1:


This is not a retain cycle. A retain cycle would be

self -> block -> self

In this case we have

animation framework -> block
block -> self

where the first retain is only temporary - the block gets released when the animation ends. Even if a retain cycle happens, it will be only temporary and it won't prevent object deallocation.




回答2:


You need to use __weak when retain cycle is possible. This is not that case because animations block is not retained by self.

Another situation to use __weak is a prolonged action that will call our block after completion and self can be deallocated during this action. For example, some network request will call interface update for our view controller in completion block. User can exit our screen during request. In this situation no need to retain self with a block, it's better to use weak self. But using animation blocks is not this situation too.




回答3:


No, it won't create a retain cycle, because the block (closure) is not attached to self.
For more information, please check out Apple's Automatic Reference Counting.



来源:https://stackoverflow.com/questions/29770743/do-we-need-to-use-weak-self-inside-uianimationblocks-in-arc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!