Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C formatting string for boolean?

People also ask

How do you set a Boolean value in Objective C?

To set a BOOL, you need to wrap the number in a value object with [NSNumber numberWithBool:NO] . But there's little reason to do that. Key-Value Coding is a roundabout way to accomplish this. Either do self.

How do I print a Boolean value?

The println(boolean) method of PrintStream Class in Java is used to print the specified boolean value on the stream and then break the line. This boolean value is taken as a parameter. Parameters: This method accepts a mandatory parameter booleanValue which is the boolean value to be written on the stream.

What is Boolean in Objective C?

Boolean, in Objective-C, is a hold over data type from the C language. Both in C, and hence in Objective-C, 0 (zero) is treated as “false” and 1 (one) as “true”. C has a Boolean data type, bool (note: the lowercase), which can take on the values of true and false.


One way to do it is to convert to strings (since there are only two possibilities, it isn't hard):

NSLog(@" %s", BOOL_VAL ? "true" : "false");

I don't think there is a format specifier for boolean values.


I would recommend

NSLog(@"%@", boolValue ? @"YES" : @"NO");

because, um, BOOLs are called YES or NO in Objective-C.


Use the integer formatter %d, which will print either 0 or 1:

NSLog(@"%d", myBool);

In Objective-C, the BOOL type is just a signed char. From <objc/objc.h>:

typedef signed char BOOL;
#define YES         (BOOL)1
#define NO          (BOOL)0

So you can print them using the %d formatter But that will only print a 1 or a 0, not YES or NO.

Or you can just use a string, as suggested in other answers.


Add this inline function to your .h file:

static inline NSString* NSStringFromBOOL(BOOL aBool) {
    return aBool? @"YES" : @"NO";
}

Now you are ready to go...

NSLog(@"%@", NSStringFromBOOL(BOOL_VAL));