views:

502

answers:

2

When writing an abstract class, or a class that doesn't get instantiated directly... do you tend to write a dealloc method in the abstract class and release where appropriate, and then allow for children to call [super dealloc] and then worry about only instance variables they add which aren't part of the super class?

How do you folks manage memory with abstract classes?

I'm thinking something along the lines of:

@interface ClassA : NSObject {
    NSArray *foo;
}
@end

@implementation ClassA
- (void) dealloc {
    [foo release];
    [super dealloc];
}
@end

@interface ClassB : ClassA {
    NSArray *bar;
}
@end

@implementation ClassB
- (void) dealloc {
    [bar release];
    [super dealloc];
}
@end

Please pardon any syntactical errors, I just wrote this up on the fly. Does the above make sense or should memory be managed differently? GC isn't an option as I'm doing this on the iPhone.

+9  A: 

Yes, you take responsibility for yourself, not for super or subclasses.

Stephan Eggermont
+1  A: 

Saying the same thing as Stephan, but from a different angle: Avoid putting alloc and release in different places as much as possible (init and dealloc being the main exceptions). That goes double for putting them in different classes, as in your case of a class and its superclass.

The superclass should not release objects that its subclasses create.

Peter Hosey