使用弱引用时,为什么ARC自动释放? [英] Why does ARC autorelease when using weak references?

查看:111
本文介绍了使用弱引用时,为什么ARC自动释放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么ARC无法使用常规版本?

Why can't ARC use a regular release?

示例:

[weakObject doSomething];

据我了解,ARC将其转换为:

From what I understand, ARC turns this into:

Object *strongObject = objc_autorelease(objc_loadWeakRetained(weakObject));
[strongObject doSomething];

为什么ARC不这样做呢?:

Why doesn't ARC do this instead?:

Object *strongObject = objc_loadWeakRetained(weakObject);
[strongObject doSomething];
objc_release(strongObject);

我想消除ARC中尽可能多的自动发行版.我使用GCD进行了很多异步线程处理,最终不得不大量添加自动释放池:

I'd like to do away with as many autoreleases in ARC as possible. I do a lot of async threading with GCD and I end up having to add autorelease pools a lot:

dispatch_async(self.myQueue, ^{
    @autoreleasepool{
        [weakObject doSomethingBig];
    }
});

推荐答案

我无法解释ARC编译器为什么这样做,但是 如果我正确理解了生成的汇编代码,请使用以下模式

I cannot explain why the ARC compiler does it this way, but if I understand the generated assembly code correctly, using the following pattern

dispatch_async(self.myQueue, ^{
    Object *strongObject = weakObject;
    [strongObject doSomething];
});

被翻译成objc_loadWeakRetained(),...,objc_release(),因此对象 没有放入自动释放池中.

is translated into objc_loadWeakRetained(), ..., objc_release(), so that the object is not put into an autorelease pool.

这篇关于使用弱引用时,为什么ARC自动释放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆