Search code examples
objective-cpropertiesbooleanlazy-initialization

property doesn't set after lazy initialization objective-c


I have a BOOL property and at the start this property equals NO. I want to set this property to YES from the start of my program, but with opportunity to toggle it. For this, I made this getter:

-(BOOL)turn
{
    if(!_turn)
        _turn = YES;
    return _turn;
}

This getter set my turn property to YES, but it makes it "constant", always YES. Why?

I thought

if(!_turn)

construction is specially for the reason where you want set the "not set yet" object value

Can you answer me why this is so? And how can I set my property value to what i want. Thanks.


Solution

  • Look at your action table:

    turn:     False          True
    !turn   turn = YES      Do Nothing
    

    When _turn is false, you flip it too true. When _turn is true, you do nothing (there's no else statement). Then you return the value of _turn. So yea, you are returning true in all cases.

    To be honest, the design is not very good. If you want to set the initial value of the variable to a certain value, do that in the init method. Then provide another method that simply toggles the value:

    -(BOOL) toggleTurn {
      _turn = !_turn;
      return _turn;
    }