Could you explain the difference?
Could you explain the difference?
With C, you are forced to care who actually allocated something and figure out a protocol for dealing with getting it released.
With Objective C, I can allocate something, hold my reference for the duration of the call, release my reference and return it. If the caller wants a reference, they can then grab it; if they don't, it will get deleted.
A retain count (a count on other parties with an interest in an object) is maintained by the runtime. When the retain count reaches zero, the object is freed. When an object is created (using alloc or copy), it has a retain count of 1. Another object can express its interest by calling the "retain" method. When it is done, the "release" method should be called.
If an object is being returned, but shouldn't be freed right away, there is a mechanism called "autorelease" where the call to release is delayed until the end of the current runloop, giving other objects a chance to retain the returned object.
Cocoa uses autorelease pool for short-lived objects, so most of the time you don't have to free them.
For long-lived objects you can use synthesized properties which handle retain/release for you.
In other cases you "guard" your use of object with retain/release. You can use these in pairs in the same place, rather than having malloc() in one part of the program, and free() in another.
You can freely pass reference to an object without worrying that you might free it while it's still referenced somewhere else. You don't have to think about ownership of an object.