Reputation: 133
Let's say that I made a custom UIView
subclass that has a property named imageView
.
I have synthesized the imageView
as follows:
@synthesize imageView = _imageView;
Is it safe to use _imageView
instead of self.imageView
in all of my custom class methods?
Upvotes: 1
Views: 109
Reputation: 81858
No, it's not safe to directly access the ivar. Just to make it clear:
_imageView
is short for self->_imageView
: direct ivar access.self.imageView
is short for [self imageView]
: using the accessor method.Using the accessor from within the class implementation gives you the following advantages:
atomic
properties it safe to use the returned value even if another thread is using the setter at the same time.copy
when assigning to ivars that back properties that are declared to copy
their values.Upvotes: 3
Reputation: 14068
It is sort of save but not good practice. You should use _imageView only in the setter and getter itself andn in init. Especially when you may whant to subclass your class later. The subclass may intentionally overwrite the getter and setter methods. In that case _imageView may not contain what you expect. Use self.imageView. That will invoke the accessors
Upvotes: 0
Reputation: 21902
It is safe assuming you are not overriding the accessors. If you provide an alternate behavior for -setImageView
for example, then calling the ivar
directly will skip that behavior. As a general design rule, I tend to use the accessor method rather than the ivar directly. It's less prone to unintended side effects and plays nicer with inheritance in the cases where you do override an accessor.
Upvotes: 1