aneuryzm
aneuryzm

Reputation: 64844

Is this if statement correct, or is it redundant?

I've a simple question about if statement in Objective - C.

Is this if statement correct, or is it redundant and I don't need to specify ==YES ?

NSNumber *boolean = [NSNumber numberWithBool:YES];
if (boolean == YES) ...

thanks

Upvotes: 2

Views: 2042

Answers (3)

Maurício Linhares
Maurício Linhares

Reputation: 40333

No, it isn't correct and it isn't going to generate the output you think it is. NSNumber * boolean is a pointer to an object in memory while YES is a scalar value; they should not be compared with ==.

If you type this code you'll also get the following warning:

warning from comparison

The correct way to do it would be:

NSNumber *boolean = [NSNumber numberWithBool:YES];
if ( [boolean boolValue] ) {
  // do something
}

But this statement itself does not make much sense, since you should be comparing the BOOLs and not NSNumber -- there is no need to use the NSNumber in there.

Upvotes: 2

Steven Fisher
Steven Fisher

Reputation: 44886

This won't work. An instance of NSBoolean is an object, and will be non-NULL whether YES or NO.

There's two good ways to check the value of a NSBoolean.

The first is to use boolValue:

NSNumber *boolean = [NSNumber numberWithBool:YES];
if ([boolean boolValue] == YES) ...
if ([boolean boolValue]) ... // simpler

The second is to use the identity of the object returned:

NSNumber *boolean = [NSNumber numberWithBool:YES];
if (boolean == (id)kCFBooleanTrue) ...

The latter is faster; it relies on there being only one each of NSBoolean YES and NSBoolean NO on the system. These have the same values as kCFBooleanTrue and kCFBooleanFalse. I've read this is safe forever, but I'm not sure it's part of Apple's published documentation.

Upvotes: 0

Evgeny Shurakov
Evgeny Shurakov

Reputation: 6082

You compare pointer and integer, which won't lead you to the result you want.

Example:

NSNumber *boolean1 = [NSNumber numberWithBool:YES];
if (boolean1) {
    // true
}

NSNumber *boolean2 = [NSNumber numberWithBool:NO];
if (boolean2) {
    // this is also true
}

if ([boolean1 boolValue] && ![boolean2 boolValue]) {
    // true
}

Upvotes: 5

Related Questions