objective C underscore property vs self

前端 未结 4 1404
伪装坚强ぢ
伪装坚强ぢ 2021-01-04 00:28

I\'m was playing around with the standard sample split view that gets created when you select a split view application in Xcode, and after adding a few fields i needed to ad

4条回答
  •  一生所求
    2021-01-04 01:00

    The properties are basically a way of the compiler to generate a setter and getter for a given instance variable.

    So when you use something like:

    id detailItem = self.detailItem;
    

    what you are doing under the hood is:

    id detailItem = [self detailItem];
    

    Same for:

    self.detailItem = otherDetailItem;
    

    would be:

    [self setDetailItem:otherDetailItem];
    

    So when you write the setter yourself.. you get in an infinite loop since you access the method itself in itself. You can freely make use of the 'self.' notation in your class, just not when you're overriding the setter or accessor because of the mechanism I described above.

    Cases in a class where I use the . notation over simply accessing the ivar is when I change the value, you never know inside your class what needs to happen when you change the value. do you have something in terms of a status that should notify some delegate that a status changed? Usually this is not the case, however, just by using the . notation you are making sure that in the future you won't have to refactor some code if you did decide to do some magic in your setter method.

提交回复
热议问题