My base class has properties that are used by a subclass. where should Release be called? In the original base class or the class that inherits it?
I'm pretty new to Objective-C, so I'm also curious what the best answer is here. I would think that you should set the property to nil
in the parent class -dealloc
, where the property is synthesized. If you're retaining it in the subclass for some reason, you should also release it in the subclass, but setting the property to nil
in the superclass shouldn't have any negative side effects.
I would say that each class manages it's own properties. So subclass class should release it's properties and base class releases it's own.
Once subclass is released it will not access base class properties, it technically does not exists anymore. Standard way of writing dealloc is:
- (void)dealloc
{
// release my stuff, after this line
// I don't exist and do not need to access any of my properties
[super dealloc];
}
If the properties are only used by the subclass, they should be defined in the subclass (not the parent class) and the subclass should release them within it's -(void)dealloc function. You'd have something like this:
- (void)dealloc
{
[username release];
[password release];
[super dealloc];
}
Note that we don't call dealloc on the properties! We just call "release" which signifies that we no longer will be using them and the system can clean them up (providing nobody else is using them).
In a given block, the number of calls to retain, copy, alloc should be balanced by calls to release, autorelease. If you retain something in the subclass, release it in the subclass, and if in the base class...
I'm paraphrasing that from memory from an article on stepwise.
Short answer: In the base class.
Long answer: Objects are "owned" by other objects. To own an object, you have to allocate or retain it (with retain, alloc, new, or copy). The owner is responsible for disposing of the memory with a release or autorelease. There should be one release/autorelease for every allocation/retain.
It is Cocoa convention that only methods that begin with "new" and "copy" return objects that have been allocated/copied/retained but are not owned by the method's receiver. The owner is then the object that called the "new" or "copy" function.