Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C Bool Literals and Macros

Tags:

objective-c

Disclaimer: limited knowledge of Objective-C (passing curiosity).

if (@YES)

vs

if (YES)

What's the difference?

From what I understand, @YES is a bool object literal, and YES is a macro that expands to 1? Is this correct? If so, why use @YES instead of YES or vice versa?

like image 577
Aristides Avatar asked Sep 18 '25 22:09

Aristides


1 Answers

@YES is a shortcut for [NSNumber numberWithBool:YES], so this:

if (@YES)

actually means

if ([NSNumber numberWithBool:YES] != nil)

Note, that it doesn't matter what number (or bool value) that is. You just test that it's a valid object. Even @NO will evaulate to YES if you test it like that, because it's a non-nil NSNumber instance:

if (@NO) NSLog(@"test");

Output:

2013-12-07 21:02:49.828 MyApp[37512:70b] test

Long story short: Don't use @YES or @NO like that, they will not behave as you would expect.

like image 99
DrummerB Avatar answered Sep 21 '25 06:09

DrummerB