首页 > 代码库 > Automatic Reference Counting

Automatic Reference Counting

- (id)allocObject {        id obj = [[NSObject alloc] init];    return obj;}- (id)object {    id obj = [[NSObject alloc] init];    [obj autorelease];    return obj;  }id obj1 = [obj0 allocObject];id obj2 = [obj0 object];     

obj1持有对象,obj2不持有对象。

通过使用autorelease,可以使取得的对象存在,但自己不持有对象。(如何做到的?)

[obj2 retain];

通过retain方法将调用autorelease方法取得的对象变为自己持有。(retain多次会怎样?)

NSObject简化版alloc:

struct obj_layout {    NSUInteger retained;};+ (id)alloc {        int size = sizeof(struct obj_layout) + 对象大小;    struct obj_layout *p = (struct obj_layout *)calloc(1, size);    return (id)(p + 1);}

技术分享

Automatic Reference Counting