6

Possible Duplicate:
Objective c formatting string for boolean?

What NSLog %-specifier should be used to literally see YES or NO when printing a BOOL?

Community
  • 1
  • 1
James Raitsev
  • 92,517
  • 154
  • 335
  • 470
  • 1
    possible duplicate of [Objective c formatting string for boolean?](http://stackoverflow.com/questions/2603802/objective-c-formatting-string-for-boolean) and [BOOL to NSString](http://stackoverflow.com/questions/738524/bool-to-nsstring) – jscs Feb 27 '12 at 02:25
  • has anybody tried %hhd format specifier for BOOL its working fine for me, it prints 1 for YES and 0 for NO – ViruMax Jan 31 '14 at 07:37

2 Answers2

17
BOOL var = YES;
NSLog(@"var = %@", (var ? @"YES" : @"NO"));

BOOL is merely an alias (typedef) for signed char.

The specifiers supported by NSLog are documented here.

Emile Cormier
  • 28,391
  • 15
  • 94
  • 122
  • Right. No direct way to handle it then? :) – James Raitsev Feb 27 '12 at 02:20
  • This is the right way to do it. – sosborn Feb 27 '12 at 02:28
  • 1
    @JAM: The `YES` and `NO` that you put in your code are just `#define YES (BOOL)1` and `#define NO (BOOL)0` -- there's nothing but `signed char`s to be handled as soon as the preprocessor is done. – jscs Feb 27 '12 at 02:29
  • 1
    @sosborn : I suppose that you *could* define a wrapper class around BOOL that knows to output itself properly when the `%@` format specifier is used, but that would just be silly. :-) – Emile Cormier Feb 27 '12 at 02:40
  • @JoshCaswell : I actually did take the time to look it up in that header file, but mistyped it here. :P – Emile Cormier Feb 27 '12 at 02:41
  • 1
    Not that I'm complaining, but why do I get so many upvotes for trivial answers like this one, yet so few when it takes me an hour to compose a detailed answer with a full working example program for a complex problem? – Emile Cormier Feb 27 '12 at 02:45
  • 1
    A classic problem, @Emile. Drives me crazy, too. You might like to read about it over on Meta: http://meta.stackexchange.com/questions/31253/the-bike-shed-problem-and-so – jscs Feb 27 '12 at 02:47
  • @JoshCaswell : Hahaha, I love that Bike Shed analogy. Experienced it many times at work. – Emile Cormier Feb 27 '12 at 02:51
4

Objective-C booleans (BOOL) are simply typedefs to signed char. Therefore, they are not objects, and aren't handled any differently from other primitive numbers. If you don't care about seeing YES and NO, you can simply print them out as you would any other number (with %d, for instance). If you would like to see YES and NO, you can follow Emile's suggestion.

Itai Ferber
  • 28,308
  • 5
  • 77
  • 83