1

I've taken over an iOS objective C code base where the code predominantly uses the underscore _ to access properties within the class bypassing the self.myVariable . I'm not sure why the previous programmer did this. It seems to defeat the purpose of properties.

Besides bypassing a getter if one exists, what are the primary gains of accessing the properties via the underscore _ ?

Mary Rogers
  • 262
  • 2
  • 8
  • http://stackoverflow.com/questions/10333495/difference-between-and-self-in-objective-c have a look at this. – Forte Zhu Mar 22 '17 at 06:06
  • 2
    Possible duplicate of [Difference between \_ and self. in Objective-C](http://stackoverflow.com/questions/10333495/difference-between-and-self-in-objective-c) – Amin Negm-Awad Mar 22 '17 at 06:14
  • lot of explanation you can find for this by a single [google search](https://www.google.co.in/?gws_rd=ssl#q=difference+between+_+and+self+in+ios&*). – vaibhav Mar 22 '17 at 06:26

1 Answers1

0

The only reason to access a property directly via the underscore is to bypass the getter/setter. Functionally there generally won't be a huge difference in the majority of cases, but there are a number of advantages to accessing properties via the setters/getters (i.e. self), including:

  • Key Value Observing - if you do want to observe when a property value is changed, it'll only be possible if it's done via a setter (including default setter).
  • Versatility in the future - If you primarily access a property via self, you then have the option of creating a getter/setter down the track without having to change all your references to the property.

Bottom line, accessing and setting a property directly (via _) simply limits your options for no gain.

Edit: As Willeke has pointed out, accessing a property directly is technically faster than doing so via an accessor (via self). For the most part this difference is negligible, but there are feasibly scenarios where it's relevant.

Allan Poole
  • 378
  • 1
  • 10
  • Accessing the ivar is faster. – Willeke Mar 22 '17 at 07:29
  • Extremely marginally, though I guess there are potentially scenarios where you need to access a property multiple times and don't need the accessors. Still rather trivial compared to the potential advantages from using accessors, but I'll update my answer regardless. – Allan Poole Mar 22 '17 at 22:56
  • Also if one needs to get at the actual bits, to get the address one must use the underscore. – Cris Mar 29 '17 at 20:36