阻止自动保留,它甚至会影响自我吗? [英] Block automatic retaining, does it affect even to ivars in self?

查看:73
本文介绍了阻止自动保留,它甚至会影响自我吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我上课:

@interface A : NSObject
{
    BOOL b;
    id   c;
}
@end

并在块中引用bc,该块是否会自动保留self?还是只是bc?关于c,它可能会保留下来,但是b呢?

and reference b and c in a block, is the block retain self automatically? Or just b and c? About c, it may be retained itself, but how about b?

推荐答案

比尔的答案不太正确:

如果您有A的实例,并在该实例内创建一个块,如下所示:

If you have an instance of A and create a block inside of that instance like so:

^{
  b = YES;
}

然后将保留self(复制块时). b不是 const复制的,因为bself强烈引用,并且在块的范围内只有selfconst.

Then self is retained (when the block is copied). b is not const-copied, because b is strongly referenced by self, and only self is const within the scope of the block.

另一方面,如果您这样做:

On the other hand, if you do:

BOOL aBool = YES;
^{
  aBool = NO;
  c = [[NSObject alloc] init];
}

然后再次复制self(在复制块本身时保留const),并允许分配给c.但是,不允许 分配给aBOOL,因为aBool的值是const复制的.

Then again, self is const-copied (and retained when the block itself is copied) and the assignment to c is allowed. However, the assignment to aBOOL is not allowed, because the value of aBool is const-copied.

换句话说,编译器将bc识别为ivars,并将直接保留self而不是ivars.

In other words, the compiler recognizes the b and c are ivars, and will retain self instead of the ivars directly.

一种可以帮助我理解所发生情况的方法是记住一个对象实际上只是一个漂亮的结构,这意味着您可以通过箭头运算符从技术上访问ivars:->

One way to think about this that helps me understand what's going on is to remember that an object is really just a fancy struct, which means you can technically access ivars via the arrow operator: ->

因此,当您访问ivars时:

So when you're accessing ivars:

b = YES;

等同于 :

self->b = YES;

从这个角度来说,为什么必须保留self,但是b不是const是很合理的.这是因为b只是较大图片"的一小部分,并且为了获得b,您还必须同时包含所有self(因为复制结构的一部分实际上没有任何意义)在这种情况下).

In that light, it makes perfect sense why you have to retain self, but b is not const. It's because b is only a slim part of the "bigger picture", and in order to get b, you must necessarily include all of self as well (since copying part of a struct doesn't really make sense in this context).

这篇关于阻止自动保留,它甚至会影响自我吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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