开发者

Objective-C retain counts clarification

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.

And now I'm in a bit of code (I'm doing iPhone development) th开发者_StackOverflowat 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?

Thanks!


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?

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.

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.

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!

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.

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 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.


If you haven't already I highly recommend you familiarize yourself with the Memory Management Programing Guide from Apple

In there you will find a section specifically on retain counts

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜