Objective-C保留计数澄清 [英] Objective-C retain counts clarification

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

问题描述

我有点理解保留数的含义.但并非完全如此.我在Google上花了很多时间试图理解,但我仍然没有.

I kind of understand what's retain counts for. But not totally. I looked on google a lot to try to understand but still I don't.

现在我有一些代码(我正在做iPhone开发),我认为我应该使用它们,但并不完全知道如何使用.

And now I'm in a bit of code (I'm doing iPhone development) that I think I should use them but don't know totally how.

有人可以给我一个快速而良好的示例,说明如何以及为什么使用它们吗?

Could someone give me a quick and good example of how and why using them?

谢谢!

推荐答案

我听过的最好的解释是亚伦·希勒加斯(Aaron Hillegass):

The best explanation I ever heard was from Aaron Hillegass:

把对象想像成狗.您需要为狗拴上皮带以防止其逃跑和消失,对吧?

Think of the object as a dog. You need a leash for a dog to keep it from running away and disappearing, right?

现在,将retain视为皮带.每次调用retain时,都会在狗的项圈上添加一条皮带.您是在说:我希望这只狗留在身边."您对皮带的保持可以确保狗一直呆到您完成它为止.

Now, think of a retain as a leash. Every time you call retain, you add a leash to the dog's collar. You are saying, "I want this dog to stick around." Your hold on the leash insures that the dog will stay until you are done with it.

想想release是从狗的项圈中去除一条皮带.除去所有的皮带后,狗便可以逃走了.无法保证狗会再出现.

Think of a release as removing one leash from the dog's collar. When all the leashes are removed, the dog can run away. There's no guarantee that the dog will be around any longer.

现在,假设您打电话给retain,并在狗身上绑上皮带.我也需要狗,所以我与您同行并开始训练他.养完狗后,请呼叫release并删除皮带.即使我仍在训练他,也没有皮带牵引绳,狗也逃走了!

Now, say you call retain and put a leash on the dog. I need the dog, too, so I walk along with you and start training him. When you are done with the dog, you call release and remove your leash. There are no more leashes and the dog runs away, even though I was still training him!

相反,如果我在开始训练狗之前先给狗叫retain,那么我的项圈上会有第二根皮带.当您打电话给release并删除皮带时,我仍然有一只狗,那只狗还不能消失.

If, instead, I call retain on the dog before I start training him, I have a second leash on the collar. When you call release and remove your leash, I still have one and the dog can't go away just yet.

通过调用retain并在其项圈上放另一个皮带,不同的对象可以拥有"狗.每个对象都确保在完成处理之前,狗不会走开.直到所有的皮带都被去除,狗才能走开.

Different objects can "own" the dog by calling retain and putting another leash on its collar. Each object is making sure that the dog doesn't go away until it is done with it. The dog can't go away until all of the leashes have been removed.

自动释放池变得更加复杂,但是简单地说,您可以考虑调用autorelease来将皮带束缚给培训师.您不再需要那只狗,但是您还没有立即移除皮带.培训师稍后将脱掉皮带;仍然不能保证狗在您需要时会在附近.

Autorelease pools get more complicated, but simplistically you can think of calling autorelease as handing your leash to a trainer. You don't need the dog anymore, but you haven't removed your leash right away. The trainer will take the leash off later; there is still no guarantee that the dog will be around when you need him.

这篇关于Objective-C保留计数澄清的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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