Objective-C formatting string for boolean?

后端 未结 9 1724
情深已故
情深已故 2020-12-13 11:38

What formatter is used for boolean values?

EDIT:

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

相关标签:
9条回答
  • 2020-12-13 12:02

    I created a category of NSString with this

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

    And use it like this:

    [NSString stringWithBool:boolValue];
    
    0 讨论(0)
  • 2020-12-13 12:07

    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));
    
    0 讨论(0)
  • 2020-12-13 12:11

    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.

    0 讨论(0)
  • 2020-12-13 12:11

    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...

    0 讨论(0)
  • 2020-12-13 12:16

    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.

    0 讨论(0)
  • 2020-12-13 12:18

    I would recommend

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

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

    0 讨论(0)
提交回复
热议问题