Reference Counting of self in Blocks

百般思念 提交于 2019-12-12 08:58:11

问题


I'm trying to get my head around how object lifetime and reference counting interact with code blocks. In the following code I'm just doing a simple animation that flashes as the top view on a UINavigationController's stack is swapped. The tricky part is that the popped view controller is the one where this code is defined.

[UIView animateWithDuration:0.2 
        animations:^{self.navigationController.view.alpha = 0.0;}
        completion:^(BOOL finished){ 
                UINavigationController *navController = self.navigationController;  

                [self.navigationController popViewControllerAnimated:NO]; 
                [navController pushViewController:nextView animated:NO];
                [nextView release];

                [UIView animateWithDuration:0.2 
                        animations:^{navController.view.alpha = 1.0;}];                    
                 }];    

My question is (ignoring what the animation looks like), is this the correct way to do this from a memory management perspective. In particular:

(1) When using this approach for the pop+push cycle, is it correct that it is no longer necessary to retain self, as in other similar examples that do not use blocks?

(2) Does invoking animateWithDuration:... with the these blocks retain the defining view controller (self) until the blocks execute?


回答1:


(1) When using this approach the the pop+push cycle, is it correct that it is no longer necessary to retain self, as in other similar examples that do not use blocks?

It is correct. These blocks automatically retain self, navController and nextView if nextView is local variable.

(2) Does invoking animateWithDuration:... with the these blocks retain the defining view controller (self) until the blocks execute?

These blocks are copied to heap from stack by this method. And these blocks are released after execution. And then self, navController and nextView are released from these blocks.



来源:https://stackoverflow.com/questions/5395743/reference-counting-of-self-in-blocks

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