Nick Keroulis
Nick Keroulis

Reputation: 133

Objective-C using the synthesized value

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

Answers (3)

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81858

No, it's not safe to directly access the ivar. Just to make it clear:

  1. _imageView is short for self->_imageView: direct ivar access.
  2. self.imageView is short for [self imageView]: using the accessor method.

Using the accessor from within the class implementation gives you the following advantages:

  • A subclass that overrides the property accessors is not bypassed.
  • KVO compliance is kept intact.
  • For atomic properties it safe to use the returned value even if another thread is using the setter at the same time.
  • Object ownership semantics are handled correctly. That's mostly important under MRC (non-ARC), but even under ARC it's still easy to forget the copy when assigning to ivars that back properties that are declared to copy their values.

Upvotes: 3

Hermann Klecker
Hermann Klecker

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

mprivat
mprivat

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

Related Questions