Understanding retain and release keywords in Objective-C 2.0 is a challenge. I came across an interesting analogy on retain and release, by Aaron Hillegass. His analogy has been quoted in one of the topic threads at StackOverflow. The analogy compares removing and attaching a leash on dog when “release” and “retain” are called.
The extract goes like this…
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.
You can read this extract here. Pretty enjoyable.