Objective-C formatting string for boolean?

浪子不回头ぞ 提交于 2019-11-27 11:01:20

问题


What formatter is used for boolean values?

EDIT:

Example: NSLog(@" ??", BOOL_VAL);, what is ?? ?


回答1:


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.




回答2:


I would recommend

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

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




回答3:


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

NSLog(@"%d", myBool);



回答4:


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.




回答5:


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));



回答6:


Format strings for use with NSLog and [NSString stringWithFormat] are documented here:

http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html

BOOL/bool/boolean are not even mentioned...




回答7:


Just add the below function and pass it the BOOL value and method will return back the NSString

- (NSString *)boolValueToString:(BOOL)theBool {
    if (theBool == 0)
        return @"NO"; // can change to No, NOOOOO, etc
    else
        return @"YES"; // can change to YEAH, Yes, YESSSSS etc
}



回答8:


I believe the easiest way to do this is:

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

@(expression)

Dynamically evaluates the boxed expression and returns the appropriate object literal based on its value (i.e. NSString for const char*, NSNumber for int, etc.).




回答9:


I created a category of NSString with this

+ (instancetype)stringWithBool:(BOOL)boolValue {
return boolValue ? @"YES" : @"NO";
}

And use it like this:

[NSString stringWithBool:boolValue];


来源:https://stackoverflow.com/questions/2603802/objective-c-formatting-string-for-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!