Difference between _property and self.property

前端 未结 3 493
轻奢々
轻奢々 2020-12-19 21:22

I\'m slightly confused as to the proper conventions when dealing with properties. I\'ll illustrate my question through an example. So from the example below I know that func

相关标签:
3条回答
  • 2020-12-19 21:45

    When you write out @synthesize loan = _loan; it is basically shorthand to say that what you are synthesizing is = to a private member it would be similar to the verbose way of coding it below:

    //ClassA.h
    @interface ClassA: UIViewController {
        double _loan;
    }
    
    @property double loan;
    @end
    
    //ClassA.m
    @implementation ClassA
    @synthesize loan = _loan;
    

    It is good practice to write it out this way so you can clearly have a '_' to signify your private members within your class code but when exposing this as a property to other classes that shouldn't be shown.

    0 讨论(0)
  • 2020-12-19 21:56

    _loan is a variable and assigning a value to it has no particular side effect.

    self.loan = self.loan + 250.00 is essentially the same as writing [self setLoan:[self loan] + 250.00] in that methods are called that may do other things than simply set or get the value of a variable. The extra things those methods do depend on whether you write custom versions of them (the setters and the getters) or use @synthesize to create them and, if you use @synthesize, what attributes you apply in the @property declaration.

    0 讨论(0)
  • 2020-12-19 22:04

    You should never use direct reference to a variable when accessing a property. Always go for self.property in your code.

    If you use _property you are not making use for your getters and setters. In this case you are just wasting @synthesize use.

    self.loan = self.loan + 250.00; //Exhibit A

    This should be right approach.

    0 讨论(0)
提交回复
热议问题