In my previous blog, I covered how C# handles memory management. In this one, I'll explain how Cocoa handles memory management and why I feel it is a better way to do things than the C# way.
In C#, you allocate objects on the heap using the 'new' operator. This creates an object on the heap and returns a 'handle' to the object. This 'handle' to the object is really just a disguised pointer. The C# runtime is still using pointers, just like C++ does. The only difference is that C# 'hides' the fact that it's a pointer from the user. This is one of the reasons I emphasized so strongly in my previous blog about what makes a good programmer, the importance of understanding pointers. C# users are using pointers, they just don't realize it! Pointers are still relevant in C#, even though they don't appear to be there. They actually are. This pointer to the newly allocated object is then passed around (with it's true pointer nature hidden from the programmer) and the programmer uses the object however he wants. Then when the programmer is done with this pointer he simply stops using it somewhere. The C# runtime is responsible for figuring out when the object is not being used anymore. Once it figures out that the object is no longer used, it addes that pointer to a list of memory blocks that can be deleted. Eventually that memory block gets deleted during idle processing. (which can be a long time off in a cpu intensive application). Essentially, the C# runtime uses an internal reference counting system to keep track of the lifetime of the pointer. Whenever another copy of that pointer is used, the reference count is increased. Whenever the copy of that pointer is no longer used, the reference count is decreased. When the reference count reaches 0, the object is no longer being used and it gets put in the list of memory blocks to eventually be freed.
Cocoa does this differently. Cocoa's way is sort of a 'middle ground' between the very low level C++ way of memory management (do everything yourself) and the C# way of memory management (the runtime does everything). In Cocoa, all objects are reference counted as well, but the difference is that YOU are responsible for the reference counting. If you need to save a copy of the pointer, you increase it's reference count by calling the 'retain' method on that object. When you are done with the pointer, you call the 'release' method on that object. Whenever 'release' is called, if the reference count hits 0, the object is deleted immediately. You still create the object using the 'new' method, but you 'delete' it using the 'release' method. Essentially, the reference counting takes care of some of the lifetime issues involved in managing pointers, but ultimately, YOU control when an object is deleted. This makes for a much more efficient program when it comes to memory usage. Yes, the Cocoa way is a bit more work, but I feel it is a small price to pay for efficiency.