0

I might be going mad here, but previously when using a BOOL I would do something like this :

BOOL myBool

if (myBool) {
  NSLog@"My Bool is YES";
}

I.e I would assume that if myBool is equivalent to saying if myBool is YES.

Under iOS7 though I am seeing the log statement trigger even when the value of myBool is never explictily set. If it is set to NO or YES the code behaves as expected.

Has something changed here under iOS7 ?

EDIT

Just to add that this moment of madness was caused but the fact that I had been elsewhere initialising BOOLs from NSUserDefaults boolForKey method, which will return NO if no value is found for that key.

GuybrushThreepwood
  • 5,598
  • 9
  • 55
  • 113
  • You forgot some parenthesis and a semicolon. And don't add tags to your title. – DrummerB Dec 09 '13 at 12:27
  • If you log out the value of myBool, you will see it has a garbage value. Any non-zero value is considered true. See this question: http://stackoverflow.com/questions/2919745/default-value-of-bool – Tim Dec 09 '13 at 12:30
  • 2
    When you use Bool without initialising Xcode shows warning that 'Variable 'myBool' is uninitialized when used here'. initialize the bool variable and then use the if condition. – Suhit Patil Dec 09 '13 at 12:33
  • I don't get this warning for some reason. – GuybrushThreepwood Dec 09 '13 at 12:41
  • 2
    @Ohnomycoco It's a warning (one of many) that can be turned on and off in Xcode. Look for `GCC_WARN_UNINITIALIZED_AUTOS` – Abizern Dec 09 '13 at 12:42

2 Answers2

7

If myBool is never explicitely set and it's a local variable, then its value is UNDEFINED. Therefore, it can evaluate to either YES or NO.

Aren't you getting some compiler warnings?

Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • No compiler warnings. That makes sense - sometimes it is Yes and sometimes No. I'm guessing in the past I've always initialised the Bool's value somehow. – GuybrushThreepwood Dec 09 '13 at 12:33
  • 2
    @Ohnomycoco `Project` - `Build Settings` - `Apple LLVM 5.0 - Warnings - All languages` - `Unitialized Variables`. – Sulthan Dec 09 '13 at 13:05
0

BOOL myBool is not initialised to any value in your code so it may have any random values either YES or NO..

Initialize your myBool to some value first..

Dinesh
  • 929
  • 7
  • 25