1. Clearly identify which object owns an object instance. An instance is responsible for deallocating whatever it owns.
@interface Expedition : NSObject {}
// Expedition owns this string
@property (nonatomic,retain) NSString *name;
// Something else owns this object
@property (nonatomic,assign) ShipType *ship;
@end
@implementation Expedition
-(void) dealloc {
// release the objects we own
[name release];
// Since Obj-C uses reference counting
// this can lead to strange behavior
// Other objects can "retain" name and therefore when we release
// "name" it doesn't guarantee that it will be dealloc'd
[super dealloc];
}
@end
// Expedition owns this string
@property (nonatomic,retain) NSString *name;
// Something else owns this object
@property (nonatomic,assign) ShipType *ship;
@end
@implementation Expedition
-(void) dealloc {
// release the objects we own
[name release];
// Since Obj-C uses reference counting
// this can lead to strange behavior
// Other objects can "retain" name and therefore when we release
// "name" it doesn't guarantee that it will be dealloc'd
[super dealloc];
}
@end
2. In every program there is 1/or more objects that are singletons that only have one owner, the program itself. Every other object should be owned by these singletons. 3. Objects that have no clear owner should be added to a pool that is periodical cleared, similar to the auto-release pool from Apple's Obj-C library.
These 2 rules handle almost all situations programmers will run into when managing memory.
No comments:
Post a Comment