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?

3
  • "In this way myBool will always NO." – you seem to have missed the point of static. Commented Jul 10, 2015 at 16:04
  • "I was told..." By whom? And in what context? Commented Jul 10, 2015 at 17:54
  • 1
    The original code is absolutely fine. Whoever told you it's not safe and clean suffers from some object-oriented illness. Commented Jul 10, 2015 at 19:04

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)];

2 Comments

bool is a typename in C and C++, don't use it as a variable name.
That'll work, but I don't see the point of it all unless you really want access to that BOOL from outside the compilation unit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.