[英]Access synthesized properties when using ARC
When I declare the synthesis a property like this: 当我声明综合属性时,如下所示:
@syntesize myObject = _myObject;
I can access _myObject
directly in code, while avoiding the synthesized getters and setters. 我可以直接在代码中访问
_myObject
,同时避免使用合成的getter和setter。
However, if I synthesize the property like this 但是,如果我像这样合成属性
@syntesize myObject = myObject;
will I no longer be able to access the instance variable hidden behind = myObject
? 我将无法再访问隐藏在
= myObject
后面的实例变量吗? Should I have a preference in using one or the other. 我应该优先使用其中一种。 Because I have often experienced "
BAD_ACCESS
- problems" when using _myObject
instead of self.myObject
. 因为使用
_myObject
而不是self.myObject
时,我经常遇到“ BAD_ACCESS
问题”。
In both cases you can access the underlying ivar. 在这两种情况下,您都可以访问基础ivar。 In both cases you should avoid doing so.
在两种情况下,您都应避免这样做。 Use accessors everywhere except init, dealloc and within accessors themselves.
除了init,dealloc之外,还可以在访问器内部使用访问器。 This will avoid many headaches, with or without ARC.
无论是否使用ARC,这都可以避免很多麻烦。
That said, if you're getting EXC_BAD_ACCESS
when accessing the ivar under ARC, you likely are doing one of the following: 也就是说,如果在ARC下访问ivar时获得
EXC_BAD_ACCESS
,则可能正在执行以下操作之一:
__bridge
__bridge
assign
or __unsafe_unretained
unsafely assign
或__unsafe_unretained
If you create a property, then you should use the property accessors and avoid using the instance variable directly. 如果创建属性,则应使用属性访问器,并避免直接使用实例变量。 The only exceptions are in your
-init
and -dealloc
methods, and in most cases it's fine to use the accessors there too. 唯一的例外是
-init
和-dealloc
方法,在大多数情况下,也可以在其中使用访问器。 Don't avoid the accessors, use them. 不要避免使用访问器,请使用它们。
Using _myObject
in and of itself shouldn't cause memory management problems. 本身使用
_myObject
不会引起内存管理问题。 The cause almost certainly lies somewhere else or is much more subtle than simply using an underscore prefixed ivar name. 原因几乎可以肯定是在其他地方,或者比仅仅使用带下划线前缀的ivar名称要微妙得多。 Anyway, if you name the ivar the same as the property, you can still access the instance variable by using just its name, as usual.
无论如何,如果您将ivar命名为与属性相同的名称,则仍然可以照例使用实例变量的名称来访问它。 It's only when you access it via the accessor methods (using eg either
self.myObject
or [self myObject]
) that you're not directly accessing the ivar. 只有通过访问器方法(例如使用
self.myObject
或[self myObject]
)访问它时,才可以直接访问ivar。 You can also access it using self->myObject
, which is equivalent to just myObject
. 您也可以使用
self->myObject
来访问它,这仅相当于myObject
。
All that said, I consider it good practice to only access ivars directly inside the accessor method implementations themselves, along with init
(and dealloc
if not using ARC). 综上所述,我认为仅在访问器方法实现本身内部直接访问ivars以及
init
(如果不使用ARC,则进行dealloc
是一种好习惯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.