In comp.lang.objective-c Michael Hopkins <[EMAIL PROTECTED]> wrote: > Hi all > > I am writing some Obj-C classes and, looking at various examples, (e.g. > Learning Cocoa with Objective-C, chapter 3) it seems that some objects do > not need to implement +alloc. My previous understanding was that you needed > to implement +alloc, -init & -dealloc for all classes - or at least that it > was highly advisable. > > I guess if you don't implement +alloc then the message gets sent up to the > superclass (usually NSObject in our case). If someone could enlighten me > here on the practical implications of these choices and best practice (for > instance, does it make a difference if your class contains instance > variables and whether they are heap allocated or not) then that would be > very helpful.
You should never override +alloc. +alloc is just a convenience method for +allocWithZone: with a NULL argument, so if you need to override one, you should override +allocWithZone:. However, there is basically never a reason to do this. Allocating objects is generally something where the base class does it right and you should have no need to modify its behavior when doing so. Override -init or another initializer when you need to do your own initialization. Normally you would do this if you need to set up the initial values of your instance variables, subscribe to notifications, start timers, etc. The runtime will zero-fill your instance variables automatically, so if that's all you need then there is no need to override any initializer. Override -dealloc if you have any instance variables pointing to objects that you own. This all comes down to memory management; if at some point you allocated, copied, or retained an object and put it in an instance variablel, you should release it here. You should also unsubscribe yourself from any notificataions, nil out delegates, and in general make sure the outside world has no references to you as you go away. Again, if none of this needs to be done then there is no need to override this method. If you do override it, don't forget to call [super dealloc] at the end, otherwise your object will not be destroyed. -- Michael Ash Rogue Amoeba Software _______________________________________________ Help-gnustep mailing list [email protected] http://lists.gnu.org/mailman/listinfo/help-gnustep
