Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

cocoa - 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) 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?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...