在ARC中,为什么self init方法是一个消耗的参数? [英] In ARC, why is self in init methods a consumed parameter?

查看:76
本文介绍了在ARC中,为什么self init方法是一个消耗的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解ARC,现在正在阅读:

I want to understand ARC, and I'm reading this:

http://clang.llvm.org/docs/AutomaticReferenceCounting.html#consumed-parameters

它表示 consumed 参数在调用之前保留,并在函数末尾(在函数体内)释放.然后说init...方法有效地标有ns_consumes_self.我看不到重点.

It says that a consumed parameter is retained before the call, and released at the end of the function (inside the function body). It then says that init... methods are effectively marked with ns_consumes_self. I don't see the point.

Foo *foo = [[Foo alloc] initWithWhatever: x];

所以alloc返回一个保留计数为1的对象,对吗?现在,再次进入init之前将其保留 ,然后在init的末尾发布,所以我们回到了1.为什么这样设计?当我想到典型的init是什么样时,我会更加困惑.

So alloc returns an object with a retain count of 1, right? Now it is retained again before going into init, and then released at the end of init, so we're back at 1. Why is it designed like this? When I think about what the typical init looks like, I get more confused.

self = [super init];
if (self) { ... } 
return self;

推荐答案

所以alloc返回一个保留计数为1的对象,对吗?现在它是 在进入init之前再次保留,然后在结束时释放 init,所以我们回到了1.为什么要这样设计?

So alloc returns an object with a retain count of 1, right? Now it is retained again before going into init, and then released at the end of init, so we're back at 1. Why is it designed like this?

可能是因为初始化器可以自由地返回指向与self最初指向的对象不同的对象的指针.一个-init方法可以说:我不喜欢这个对象,我想我会替换一个不同的对象,这完全可以.在ARC之前,这样的初始化程序将显式释放self(即使它从未保留过它),然后为它分配一些其他指针.大概,ns_consumes_self指令将负责释放传递到初始化程序中的对象,即使self更改为指向方法内的其他对象也是如此.

Probably because initializers are free to return a pointer to a different object than the one that self points to initially. An -init method can say: I don't like this object, I think I'll substitute a different one and that's perfectly OK. Before ARC, such an initializer would explicitly release self (even though it never retained it) and then assign some other pointer to it. Presumably, the ns_consumes_self directive will take care of releasing the object that was passed into the initializer even if self is changed to point to some other object inside the method.

当我想到典型的init的样子时,我会更加困惑.

When I think about what the typical init looks like, I get more confused.

可以肯定的是,这种行为可以掩盖看起来不像 typical -init方法的情况.修改self并不完全是典型的,只是允许的.

It's a good bet that the behavior is there to cover cases that don't look like a typical -init method. Modifying self isn't exactly typical, it's just permissible.

这篇关于在ARC中,为什么self init方法是一个消耗的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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