Implementing __autoreleasing ownership qualifier

__autoreleasing ownership qualifier

Assigning an object to any variables qualified with __autoreleasing is equivalent to calling the autorelease method in a non-ARC environment. Let’s see how it works with source code.

@autoreleasepool {
    id __autoreleasing obj = [[NSObject alloc] init];
}

It adds an object of NSObject class to the autorelease pool. Let’s see how the compiler translates it.

/* pseudo code by the compiler */
id pool = objc_autoreleasePoolPush();
id obj = objc_msgSend(NSObject, @selector(alloc));
objc_msgSend(obj, @selector(init));
objc_autorelease(obj);
objc_autoreleasePoolPop(pool);

It just works as I explained with Apple’s implementation. (See Chapter 1, Section “Apple’s Implementation of autorelease.”) The autorelease mechanism itself works exactly same as in a non-ARC environment although the source codes are different.

What happens if the object is not obtained by the alloc/new/copy/mutableCopy method group? Let’s see the next example with NSMutableArray class method “array”.

@autoreleasepool {
    id __autoreleasing obj = [NSMutableArray array];
}

Let’s check what is different from the previous example.

/* pseudo code by the compiler */
id pool = objc_autoreleasePoolPush();
id obj = objc_msgSend(NSMutableArray, @selector(array));
objc_retainAutoreleasedReturnValue(obj);
objc_autorelease(obj);
objc_autoreleasePoolPop(pool);

Although, objc_retainAutoreleasedReturnValue is used, other autorelease pool-related codes are exactly the same as the previous example.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值