关于ios:iVars引用强,弱或什么?

iVars references strong, weak or what?

在obj-c中,可以将属性配置为弱/强。实例变量。像下面一样-

1
2
3
@interface MyClass {
NSObject *a;
}

MyClass的对象是否保持弱引用a或强引用,或其他内容?我认为在它的目标被释放之前,IVAR是不会被释放的。为什么我们不为类ivar属性指定弱/强?


对ivar的默认引用是__strong,尽管您可以将其显式设置为__weak__strong


你的问题启发了我,我对客观记忆管理做了深入的研究。我想和你分享我从苹果医生那里得到的东西。

实例变量的默认行为

Instance variable maintains a strong reference to the objects by default

为什么我们不为类ivar属性指定弱/强?

Local variables and non-property instance variables maintain a strong references to objects by default. There’s no need to specify the strong attribute explicitly, because it is the default.
A variable maintains a strong reference to an object only as long as that variable is in scope, or until it is reassigned to another object or nil.

If you don’t want a variable to maintain a strong reference, you can declare it as __weak, like this:

1
  NSObject * __weak weakVariable;


1
2
3
4
5
@interface MyClass {
__weak NSObject *a;
__strong NSObject *a;
__unsafe_unretained NSObject *obj;
}