内存管理

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);
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 自动引用计数 自动引用计数:指内存管理中对引用采取自动计数的技术。 内存管理/引用计数 持有对象引起引用计数加...
    南京小伙阅读 1,350评论 2 3
  • 前言 从我开始学习iOS的时候,身边的朋友、网上的博客都告诉我iOS的内存管理是依靠引用计数的,然后说引用计数大于...
    盖世英雄_ix4n04阅读 581评论 0 1
  • ARC 在LLVM编译器中设置ARC为有效状态,就无需再次输入retain或者release代码 alloc,re...
    CoderLNHui阅读 398评论 0 0
  • 1. ARC的基本概念 在objc中采用automatic reference counting 机制, 让编译器...
    ZhengLi阅读 729评论 0 5
  • 死鱼说 海底石 作 说说死鱼吧 譬如他与江河的关系 譬如他永不闭合的双眸 譬如只要不油炸、水煮、气蒸都一直光滑的身...
    王自鹏阅读 177评论 0 1