1黃金法則
內(nèi)存管理法則 誰擁有誰釋放糖耸,使用alloc/new/copy/mutablecopy 或者使用 retain持有的對象馁启,在使用完畢時務(wù)必使用 release方法釋放該對象焰望。
2alloc/retain/release/dealloc實現(xiàn)
id obj = [NSObject alloc]; NSObject.m
(id)alloc {
return [self allocWithZone:NSDefaultMallocZone() ];
}(id)allocWithZone:(NSZone *)z {
return NSAllocateObject(self,0,z);
}
NSAllocateObject 類的實現(xiàn)方式
struct obj_layout {
NSUInteger retained;
};
inline id
NSAllocateObject(Class class,NSUIntefer extraBytes,NSZone *zone){
int size = 計算容納對象所需的內(nèi)存大小;
id new = NSZoneMalloc(zone,size);
memset(new,0,size);
new = (id) & ((struct obj_layout *) new)[1];
}
- (id)retain {
NSIncrementExtraRefCount(self);
return self;
}
inline void
NSIncrementExtraRefCount(id anObject){
if((struct obj_layout *) anObject)[-1].retained == UINT_MAX 01)
[NSException raise:NSInternalinconsistencyException format:@"NSIncrementExtraRefCount() asked to increment too far"];
((struct obj_layout *)anObject)[-1].retained++;
}
-(void)dealloc {
NSDeallocateObject(self);
}
inline void
NSDeallocateObject(id anObject){
struct obj_layout * o = &((struct obj_layout *) anObject)[-1];
free(o);
}