开发者

Is there a format specifier that works with Boolean values?

I want to do something like this:

NSLog(@"You got: %x", booleanValue);

where x is the specifier. But I can't find one! I want to avoid:

if (booleanValue) {
    NSLog(@"You got: YES");
}
else {
    NSLog(@"You got: NO");
}

Any ideas? The docs didn't have a Boolean specifier. %@ didn't work eithe开发者_运维知识库r.


Here are two things that work:

NSLog(@"You got: %@",booleanValue ? @"YES" : @"NO");

or you can cast:

NSLog(@"You got: %d", (int)booleanValue);

Which will output 0 or 1


You can cast it to an int and use %d:

NSLog(@"You got: %d", (int)booleanValue);

Or use something like this:

NSLog(@"You got: %@", booleanValue ? @"YES" : @"NO");


There's no format specifier that I know of. You can do this:

NSLog(@"You got: %@", (booleanValue ? @"YES" : @"NO"));

Alternately, you could write a little function or macro using the logic above that takes a BOOL and returns the appropriate string. You can then use that function in your log statements.


For os_log use

os_log("results in true/false: %{bool}d", myBool)
os_log("results in YES/NO: %{BOOL}d", myBool)

If you are on the latest OS, you can also use string interpolation. For more info look at Format Custom Values in Message Strings

As @MottiShneor pointed out, there is a more detailed list in the os_log(3) man pages:

Value type      Custom specifier         Example output
-----------------------------------------------------------------------------
BOOL            %{BOOL}d                 YES
bool            %{bool}d                 true
darwin.errno    %{darwin.errno}d         [32: Broken pipe]
darwin.mode     %{darwin.mode}d          drwxr-xr-x
darwin.signal   %{darwin.signal}d        [sigsegv: Segmentation Fault]
time_t          %{time_t}d               2016-01-12 19:41:37
timeval         %{timeval}.*P            2016-01-12 19:41:37.774236
timespec        %{timespec}.*P           2016-01-12 19:41:37.2382382823
bitrate         %{bitrate}d              123 kbps
iec-bitrate     %{iec-bitrate}d          118 Kibps
uuid_t          %{uuid_t}.16P            10742E39-0657-41F8-AB99-878C5EC2DCAA
sockaddr        %{network:sockaddr}.*P   fe80::f:86ff:fee9:5c16
in_addr         %{network:in_addr}d      127.0.0.1
in6_addr        %{network:in6_addr}.16P  fe80::f:86ff:fee9:5c16


Of course you can use the direct boolean formatting specifier %x

BOOL flag = YES;
NSLog(@"You got: %x", flag);

but at the very least, you can always rely on NSNumber objects, that 'remember' the 'type' of data they 'box' so this NSLog will also work fine:

NSLog(@"You got %@", flag? @YES : @NO);

Pay attention to the use of NSNumber literals - not strings.


On Swift, use String(describing: booleanValue)

For example: os_log("You got %@", log: .default, type: .debug, String(describing: booleanValue))


Yes

Here is the code:

NSLog(@"%hhd",BOOLvariable);

Prints 1 for Yes and 0 for No. Worked for me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜