Why do I need to write @synthesize when I provide getter and setter?

后端 未结 3 1853
别那么骄傲
别那么骄傲 2020-12-03 08:54

So the auto synthesize of properties is awesome. However, when you provide both a getter and a setter, you get an error.

@property (strong, nonatomic) NSArra         


        
3条回答
  •  暖寄归人
    2020-12-03 09:24

    I did some testing:

    Under recent Objective-c convention, you do not need to synthesize properties.

    If you do

    @property (strong, nonatomic) Business* theBiz;
    

    iOs will automatically create a private ivar variable called _theBiz;

    If you only implement a getter or a setter it seems to work just fine:

    -(void)setTheBiz:(Business *)theBiz
    {
        _theBiz = theBiz;
    }
    

    However, if you declare BOTH, even if one of them are just empty function you'll get compile error.

    -(void)setTheBiz:(Business *)theBiz
    {
        _theBiz = theBiz;
    }
    
    -(Business *) theBiz
    {
    
    }
    

    When you implement BOTH getter and setter you will get a compile error saying that therre is no such thing as _theBiz.

    That can be easily fixed by adding:

    @synthesize theBiz = _theBiz;
    

    But that defeat the whole point of this awesome new feature of Objective-c.

    I wonder if this is by design or I am just missing something. What does apple thing?

    My best guess is it's a bug.

    Guillaume's answer doesn't address that fact.

    He said that

    at least one method has been synthesized

    It seems that _theBiz would have been created if only ONE of getter or setter is set. When both are set it's no longer created and that must be a bug. In fact, none have to be set at all and the ivar will still be created.

    The only way to fix that is to explicitly do

    @synthesize theBiz = _theBiz;
    

提交回复
热议问题