Practical Memory Management
Use Accessor Methods to Make Memory Management Easier:
一般使用accessor method 来大幅度减少内存管理出现的问题,相比直接使用retain和release来说。
@interface Counter: NSObject{
NSNumber *_count;
}
@property (nonatomic, retain) NSNumber *count;
“get”accessor Method:
- (NSNumber *)count{
return _count;
}
“set”accessor Method:
- (void)SetCount: (NSNumber *)newCount{
[newCount retain];
[_count release];
_count = newCount; //Make the new assignment;
}
Use Accessor Methods to Set Property Values:
推荐使用:
-(void)reset{
NSNumber *zero = [[NSNumber alloc] initWithInteger:0];
[self setCount:zero];
[zero release];
}
或
-(void)reset{
NSNumber *zero = [NSNumber numberWithInteger:0];
[self setCount:zero];
}
不推荐使用(将不遵从KVO):
-(void)reset{
NSNumber *zero = [[NSNumber alloc] initWithInteger:0];
[_count release];
_count = zero;
}
Do not Use Accessor Methods in Initializer Method and dealloc
Use Weak References to Avoid Retain Cycles:
"父"对象保持对"子"对象的强引用,"子"对象保持对"父"对象的弱引用,以避免出现Retain Cycles.
Cocoa 的弱引用包含但不限于: table data sources, outline view items, notification observers, miscellaneous targets and delegates.在弱引用时,send message 时需要特别小心对象是否有效。
Avoid Causing Deallocation of Objects You’re Using:
1. 当一个对象从基本的集合类里移除的时候,这个对家就会被马上释放掉,如果这个集合是这个对象的唯一owner的话
heisenObject = [array objectAtIndex:n];
[array removeObjectAtIndex:n]; //heisenObject could now be invalid.
2. 当“parent obejct”释放时,“children object” 也会释放
id parent = <#create o parent object#>;
// …
hesienObject = [parent child];
[parent release];//Or, for example: self.parent = nil;
//heisenObject could now be invalid.
通过retain你接收到的对象,然后在用完后,release这个对象,来避免出现上述的情况:
hesienObject = [[array objectAtIndex: n] retain];
[array removeObjectAtIndex:n];
//Use hesienObject….
[hesienObject release];
Do not Use dealloc to Manage Scarce Resources:
三种情况:
1. 依赖于对象的消除顺序的
2. 稀缺资源不能回收
3. cleanup 的逻辑在错误的线程执行
Collections Own the Objects They Contain:
给集合(如array, dictionary,set)添加一个项时,不需要retain,当从一个集合移除一个项时,也不需要release.