Linked by Jared White on Wed 7th May 2003 07:13 UTC
General Development Welcome back to Part 2 of Cocoa 101: Object-Oriented Programming for the Masses! I received a lot of great feedback on my previous article, and I'm looking forward to sharing with you once again what I've learned about Cocoa and the Objective-C language. If you missed Part 1 of this tutorial, read it here.
Permalink for comment
To read all comments associated with this story, please click here.
Autoreleasing & dealloc-ing
by Paolo Manna on Wed 7th May 2003 10:38 UTC

There is another (treacherous) memory error in the sample code...From the Cocoa documentation (Programming Topics - Memory Management):

It is possible for you to obtain a new object by invoking a class method of the form +className.... These class convenience methods create a new instance of the class, initialize it, and return it for you to use. Although you might think you are responsible for releasing objects created in this manner, that is not the case. Because the class method allocates the memory for the object, it is responsible for releasing that memory, thus class convenience methods should return their values autoreleased.

Thus, when you create in -init a NSCalendarDate or a NSColor through their class methods ([NCalendarDate calendarDate] & [NSColor clearColor]) you're actually getting an object that will be autoreleased in a real world application. If it doesn't fail on your tests it's because you probably don't have a running NSAutoreleasePool in place. For a correct programming, you should either:
- retain it (sensible thing to do, if you want to use it later)
- avoid a release in -dealloc (because the object will be gone anyway)

Memory management in Cocoa is wonderful when you finally manage it, but has its conventions...