Objective-C retain counts clarification

微笑、不失礼 提交于 2019-11-29 02:46:01
dmkash

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!