Objective C - Using property get accessor vs directly using iVar

前端 未结 3 734
陌清茗
陌清茗 2021-01-21 10:56

I was wondering what exactly are the differences between using the (get) accessor for reading the value of property and directly using the iVar?

Say I have a class which

3条回答
  •  难免孤独
    2021-01-21 11:46

    As you know, calling self.someString is really [self someString]. If you chose to create a property then you should use the property. There may be other semantics added to the property. Perhaps the property is lazy loaded. Perhaps the property doesn't use an ivar. Perhaps there is some other needed side effect to calling the property's getter. Maybe there isn't now but maybe this changes in the future. Calling the property now makes your code a little more future proof.

    If you have an ivar and a property, use the property unless you have explicit reason to use the ivar instead. There may be a case where you don't want any of the extra semantics or side effect of the property to be performed. So in such a case, using the ivar directly is better.

    But ultimately, it's your code, your property, your ivar. You know why you added a property. You know any potential benefits of that property, if any.

提交回复
热议问题