Should I Use self Keyword (Properties) In The Implementation?

后端 未结 2 1209
南方客
南方客 2020-12-08 23:07

I believe I understand properties for the most part. My question is, if I have a property for an instance variable, and I am setting or retrieving it from within a method in

相关标签:
2条回答
  • 2020-12-08 23:45

    If you're exposing the property to the outside world and you're using it internally you should be using the property throughout your code. The reason is encapsulation. Say you have an "Id" property for SomeObj. Say at some point you decide to replace the way Id behaves (maybe you started with Id being a member var of the class, and through evolution it becomes a piece of data that is retrieved from the database). Now you have to go through your class implementation and replace all of the references to the member var with database calls. If you had self.Id, you'd just have to override the getter.

    0 讨论(0)
  • 2020-12-09 00:06

    First, you should not use setters or getters in init or dealloc according to Apple documentation (and for good reasons).

    Other than that, you should generally use the setter for setting the variable if there is one.

    Usually I do not bother using the getter for accessing the ivar from within the implementation, but there are times when it is necessary. In particular, if you expect the getter might do some caclulation or checking, or if you want to allow for subclasses to override the behaviour.

    Certainly, using the getter in the implementation is more general and safer, but it is also typically pointless and wasteful. Make your choice.

    Using the setter is important as it gives an opertunity for other code to observe the changes (Key Value Observing), as well as subclasses a chance to override the setter and make any other adjustments required.

    However one thing I highly recommend is to use a different name for your ivar and your property. The normal convention is an underscore prefix (_), although I personally use i_ as the prefix to avoid any confusion with Apple's private usage. That way you cannot accidently use the wrong one:

    self.name // use property
    i_name // use ivar
    self.i_name // syntax error
    name // syntax error
    
    0 讨论(0)
提交回复
热议问题