dot syntax vs method syntax with getter=

后端 未结 4 414
清酒与你
清酒与你 2020-12-18 23:30

I\'m not sure how much use this question is but it seems interesting to me...

I thought that using property/synthesize statements was equivalent to me creating the ge

4条回答
  •  一整个雨季
    2020-12-19 00:12

    Property declarations are merely shorthand for regular method declarations. E.g.:

    @property int color;
    @property (getter=isOn) BOOL on;
    

    becomes these method declarations:

    - (int)color;
    - (void)setColor:(int)value;
    - (BOOL)isOn;
    - (void)setOn:(BOOL)on;
    

    You can call these methods just like any other method:

    [foo color];
    [foo isOn];
    

    Likewise, dot notation is merely informal shorthand for calling plain old methods. For example:

    x = @"Hello".length;
    x = foo.on;
    x = foo.isOn;
    

    becomes

    x = [@"Hello" length];
    x = [foo isOn];
    x = [foo isOn];
    

    Note that @"Hello".length works even though NSString does not actually declare a property named "length". By default, foo.bar always expands to [foo bar] unless bar has been declared a property with a custom getter. If bar happens to be the name of a valid method then it will work without error.

    Likewise, in your example foo.isOn works even though you don't actually declare a property named "isOn". Rather "isOn" is the name of a method that just happens to be the getter method for your "on" property.

    So, while foo.isOn may work, it's considered bad form because isOn is not actually the name of the property.

    What you cannot do is this:

    x = [foo on]; // Error
    

    because you never declare an on method.

提交回复
热议问题