如何在Objective C中打印bool类型

18
我已经为我的NSUserDefault设置了一个键为TCshow的布尔值, 我想运行一个nslog测试,以确定是否保存了该键,并尝试打印出布尔值。 这是我的代码,但它没有起作用,有什么建议吗?
- (IBAction)acceptAction:(id)sender {
//key store to nsuserdefault
self.storedKey = [[NSUserDefaults alloc] init];
[self.storedKey setBool:YES forKey:@"TCshow"];
//trying to print out yes or not, but not working...
NSLog(@"%@", [self.storedKey boolForKey:@"TCshow"]);

}

顺便说一下,这个方法是用于类似“条款和条件”滚动视图的。我想要的是,如果新用户第一次使用应用程序,那么会向他推广T&C以供接受,如果他接受了,那么值YES将保存到nsuserdefault键TCshow中,下次当他回来时,不再弹出T&C视图,直接进入登录视图。谢谢如果有人能帮我理清这个逻辑,我会非常感激...再次感谢 - sefirosu
请查看以下链接:https://dev59.com/7Ww15IYBdhLWcg3w1_YN - WeCan
7个回答

42

%@ 用于对象。 BOOL 不是一个对象。你应该使用%d

它将打印出 0 表示 FALSE/NO,打印出1表示 TRUE/YES。


2
%d 可以工作,但请记住 BOOLsigned char 而不是 int - Ankur

19

你应该使用

NSLog(flag ? @"Yes" : @"No");

这里的flag是你的BOOL


4
NSLog(@"The value is %s", [self.storedKey boolForKey:@"TCshow"] ? "TRUE" : "FALSE");

3
NSLog(@"%d", [self.storedKey boolForKey:@"TCshow"]);

0
if([self.storedKey boolForKey:@"TCshow"]){
NSLog(@"YES");
}
else{
NSLog(@"NO");

}

我认为这对你会有帮助。


0

仅为使用新语法而言,您可以将布尔值装箱为对象,以便使用%@进行打印。

NSLog(@"%@", @( [self.storedKey boolForKey:@"TCshow"] ));

0

已在另一篇帖子中回答,复制到此处:


  • 将布尔值直接转换为整数输出
BOOL curBool = FALSE;
NSLog(@"curBool=%d", curBool);

-> curBool=0

  • 将布尔值转换为字符串
char* boolToStr(bool curBool){
    return curBool ? "True": "False";
}

BOOL curBool = FALSE;
NSLog(@"curBool=%s", boolToStr(curBool));

-> curBool=False


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接