阻止自动保留,是否会影响 self 中的 ivars?
如果我有 class:
@interface A : NSObject
{
BOOL b;
id c;
}
@end
并在块中引用 b
和 c
,该块是否会自动保留 self
?或者只是 b
和 c
?对于c
,它可能会被保留,但是对于b
呢?
If I have class:
@interface A : NSObject
{
BOOL b;
id c;
}
@end
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Bill 的答案并不完全正确:
如果您有一个
A
实例并在该实例内创建一个块,如下所示:然后
self
被保留(当复制该块时) )。b
不是const
复制的,因为b
被self
强引用,并且只有self
在块的范围内是const
。另一方面,如果您这样做:
那么,
self
会被const
复制(并在复制块本身时保留)并赋值给c< /code> 是允许的。但是,不允许对
aBOOL
进行赋值,因为aBool
的值是const
复制的。换句话说,编译器将
b
和c
识别为 ivars,并将保留self
而不是直接保留 ivars。思考这个问题的一种方法可以帮助我理解正在发生的事情,那就是记住对象实际上只是一个奇特的结构,这意味着您可以在技术上通过箭头运算符访问 ivars:
->
所以当您正在访问 ivars:
等价于:
从这个角度来看,您必须保留
self
的原因完全有道理,但是b
不是const
。这是因为b
只是“大局”的一小部分,并且为了获得b
,您必须包含所有self
同样(因为复制结构体的一部分在这种情况下并没有真正意义)。Bill's answer isn't quite correct:
If you have an instance of
A
and create a block inside of that instance like so:Then
self
is retained (when the block is copied).b
is notconst
-copied, becauseb
is strongly referenced byself
, and onlyself
isconst
within the scope of the block.On the other hand, if you do:
Then again,
self
isconst
-copied (and retained when the block itself is copied) and the assignment toc
is allowed. However, the assignment toaBOOL
is not allowed, because the value ofaBool
isconst
-copied.In other words, the compiler recognizes the
b
andc
are ivars, and will retainself
instead of the ivars directly.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:
->
So when you're accessing ivars:
is equivalent to:
In that light, it makes perfect sense why you have to retain
self
, butb
is notconst
. It's becauseb
is only a slim part of the "bigger picture", and in order to getb
, you must necessarily include all ofself
as well (since copying part of a struct doesn't really make sense in this context).块中的代码将有助于回答,但假设您有类似的东西;
a
会被该块保留,并在该块被释放时被释放。b
和c
不会发生任何异常情况。如果你有类似的东西;
然后,
c
将被块保留,而b
将被块捕获为const
值(即,您将收到编译器错误:执行b = NO
)有关更多详细信息,请参阅文档;
http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/bxVariables.html%23//apple_ref/doc/uid/TP40007502-CH6-SW1
Code from the block would be helpful in answering but assuming you have something like this;
a
will be retained by the block and released when the block is released. Nothing outside the ordinary will happen withb
andc
.If you have something like;
Then
c
will be retained by the block andb
will be captured by the block as aconst
value (i.e. you would get a compiler error for doingb = NO
)For more details see the docs;
http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/bxVariables.html%23//apple_ref/doc/uid/TP40007502-CH6-SW1