0

I want to have a static boolean like in Java. This boolean only created once for the entire class, no matter how many instance it has.

I read some posts here. Some of them are suggesting that in .m file, init this variable like

static BOOL myBool = NO;

and then have a getter and a setter function. But I was told that this is not safe and clean in Objective C. A safer and cleaner way to do this is init static variable in function. But if I init it in a function, like

+(Bool)getMyBool {
    static BOOL myBool = NO;
    return myBool;
}

In this way myBool will always NO. What if I want to set this boolean afterwards? If I call static BOOL myBool again, would it give me the same boolean?

2 Answers2

2

There is nothing inherently “not safe and clean” about a global static variable in Objective-C and they are commonly used when appropriate - they are effectively Objective-C's class variables.

See Setting Static Variables in Objective-C for one way to write the getter and setter functions you mention.

Community
  • 1
  • 1
CRD
  • 52,522
  • 5
  • 70
  • 86
0

Try this

+(BOOL)resetBoolOrGet:(BOOL)reset newVal:(BOOL)newValue {
    static BOOL myBool = NO;
    if (reset) {
        myBool = newValue;
    }
    return myBool;
}

So, if you want to assign a new value to this boolean, call

[MyClass resetBoolOrGet:YES newVal:newValue];

If you only wants to get the value of that static boolean, call

[MyClass resetBoolOrGet:NO newVal:(either YES or NO)];
katie
  • 197
  • 2
  • 11