内存管理

1黄金法则
内存管理法则 谁拥有谁释放,使用alloc/new/copy/mutablecopy 或者使用 retain持有的对象,在使用完毕时务必使用 release方法释放该对象。

2alloc/retain/release/dealloc实现

id obj = [NSObject alloc]; NSObject.m

  • (id)alloc {
    return [self allocWithZone:NSDefaultMallocZone() ];
    }

  • (id)allocWithZone:(NSZone *)z {
    return NSAllocateObject(self,0,z);
    }
    NSAllocateObject 类的实现方式
    struct obj_layout {
    NSUInteger retained;
    };

inline id
NSAllocateObject(Class class,NSUIntefer extraBytes,NSZone *zone){
int size = 计算容纳对象所需的内存大小;
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);
}

你可能感兴趣的:(内存管理)