简体   繁体   中英

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?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM