参考块中的self计数 [英] Reference Counting of self in Blocks

查看:112
本文介绍了参考块中的self计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图了解对象生存期和引用计数如何与代码块交互。在下面的代码中,我只是做一个简单的动画,当UINavigationController的堆栈顶视图被交换时闪烁。棘手的部分是弹出的视图控制器是定义此代码的视图

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)当使用这种方法进行pop + push循环时,是否正确不再需要保留self,如其他类似的例子不使用块?

(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)使用这些块调用animateWithDuration:...是否保留定义视图控制器(self),直到块执行?

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

推荐答案


(1)当使用这种方法时,pop + push循环,是否正确不再需要保留self,就像其他不使用块的类似示例一样?

(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?

这是正确的。如果nextView是局部变量,这些块会自动保留self,navController和nextView。

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


(2)调用animateWithDuration:...块保留定义视图控制器(self),直到块执行?

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

这些块通过此方法从堆栈复制到堆中。这些块在执行后被释放。然后self,navController和nextView从这些块中释放。

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.

这篇关于参考块中的self计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆