简体   繁体   中英

Abstract class memory management in Cocoa

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.

是的,你对自己负责,而不是对超级或子类负责。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM