21

我想做这样的事情:

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

其中 x 是说明符。但是我一个也找不到!我想避免:

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

有任何想法吗?文档没有布尔说明符。 %@也没有用。

4

7 回答 7

37

这里有两件事有效:

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

或者你可以投:

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

哪个会输出 0 或 1

于 2011-07-19T18:23:23.500 回答
9

您可以将其转换为 int 并使用%d

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

或者使用这样的东西:

NSLog(@"You got: %@", booleanValue ? @"YES" : @"NO");
于 2011-07-19T18:21:57.853 回答
4

我知道没有格式说明符。你可以这样做:

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

或者,您可以使用上面的逻辑编写一个小函数或宏,该逻辑接受 BOOL 并返回适当的字符串。然后,您可以在日志语句中使用该函数。

于 2011-07-19T18:22:45.243 回答
4

os_log使用

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

如果您使用的是最新的操作系统,您还可以使用字符串插值。有关更多信息,请查看在消息字符串中格式化自定义值

正如@MottiShneor 指出的那样,os_log(3)手册页中有一个更详细的列表:

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
于 2021-01-14T10:01:44.647 回答
1

Swift,使用String(describing: booleanValue)

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

于 2020-01-09T20:56:24.503 回答
0

是的

这是代码:

NSLog(@"%hhd",BOOLvariable);

打印 1 表示是,0 表示否。为我工作。

于 2014-01-31T08:25:34.583 回答
0

当然,您可以使用直接布尔格式说明符 %x

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

但至少,你总是可以依赖 NSNumber 对象,“记住”它们“框”的数据的“类型”,所以这个 NSLog 也可以正常工作:

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

注意使用 NSNumber 文字 - 而不是字符串。

于 2021-04-06T08:21:10.660 回答