调用方法的方法:自动发布的基础? [英] Methods That Call Methods: Basics of Autorelease?

查看:81
本文介绍了调用方法的方法:自动发布的基础?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我以为我已经完全理解了这个主题时,我又回到了基础.

Just when I thought I've understood this topic completely, I'm back to basics.

我有一个使用(例如)stringWithFormat实例化自动释放对象的方法:

I have a method that instantiates an autoreleased object, using (for example) stringWithFormat:

return [NSString stringWithFormat:@"what"];

然后,我从另一个方法和另一个方法调用此方法,每次都在层次结构的每个级别返回此自动释放的NSString.该代码可以正常工作,并且NSString实例在层次结构的每个级别都是完整的.

Then I call this method from another method, and another method, each time returning this autoreleased NSString and in each level of the hierarchy. The code works fine and the NSString instance is intact at each level of the hierarchy.

认为,因为该实例是自动释放的,所以它可能突然在调用堆栈中的任何位置以retainCount结束(例如,其中一种方法将在已释放的对象). 我确实不能依赖此对象吗?

I thought that since the instance is autoreleased, it could suddenly end up with a retainCount of 0 at any point in the call stack (i.e., one of the methods would be working on a released object). Is it true that I cannot depend on this object?

编辑:我知道问题不太清楚.对不起.我的意思是:

I realize the question wasn't too clear. Sorry. I mean:

Method1 ---calls--->    Method2 ---calls---> Method3 ---instantiates the string---> 

推荐答案

可以假定自动释放的对象不会在分配该对象的框架下的堆栈框架中被释放.因此,在像

It is safe to assume that an autoreleased object will not be deallocated in a stack frame below the frame in which it was allocated. So, in a call stack like

method1
  method2 <== instance allocated/autoreleased here
   method3 <== safe to use here

可以安全地假定在method2中分配/自动释放的实例在method3中有效,除非您玩恶作剧并从method3中耗尽在method1中创建的池.这是因为较高帧中的自动释放池无法耗尽较低帧中的(除非由于愚蠢).当然,一旦控制权返回到method1,所有的赌注都将关闭.

it is safe to assume an instance alloc/autoreleased in method2 is valid in method3 unless you play nasty tricks and drain a pool created in method1 from method3. This is because an autorelease pool in a higher frame cannot be drained (unless by stupidness) in a lower frame. Of course, once control returns to method1, all bets are off.

在较低帧中分配的自动释放池将不包含在method2中自动释放的实例,因为在自动释放时它们可能不是活动池(尚未创建!).

Autorelease pools alloc'd in a lower frame will not contain the instance autoreleased in method2 because they could not have been the active pool (they weren't created yet!) at the time of the autorelease.

最后,除非是调用链中较低的一种方法,之间在感兴趣的方法与实例化并自动释放对象实例的方法之间创建并消耗自动释放池,您可以放心,直到运行循环结束时,封闭池才会耗尽.

Finally, unless a method lower in the call chain, between the method of interest and the method that instantiates and autoreleases an object instance creates and drains an autorelease pool, you are assured that the enclosing pool will not be drained until the end of the run loop.

这篇关于调用方法的方法:自动发布的基础?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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