如何在NSLog中打印布尔标志?

有没有办法在NSLog中打印布尔标志的值?

以下是我如何做到的:

BOOL flag = YES; NSLog(flag ? @"Yes" : @"No"); 

?:是表单的三元条件运算符:

 condition ? result_if_true : result_if_false 

在适当的地方相应replace实际的日志string

%d0为FALSE, 1为TRUE。

 BOOL b; NSLog(@"Bool value: %d",b); 

要么

 NSLog(@"bool %s", b ? "true" : "false"); 

根据数据types%@变化如下

 For Strings you use %@ For int you use %i For float and double you use %f 

布尔只不过是整数,它们只是types铸造值…

 typedef signed char BOOL; #define YES (BOOL)1 #define NO (BOOL)0 BOOL value = YES; NSLog(@"Bool value: %d",value); 

如果输出是1,否则是否

请注意,在Swift中,你可以做

 let testBool: Bool = true NSLog("testBool = %@", testBool.description) 

这将loggingtestBool = true

虽然这不是对Devang的问题的直接回答,但我相信下面的macros可以帮助那些希望loggingBOOL的人。 这将注销bool的值,并自动用variables名称标注它。

 #define LogBool(BOOLVARIABLE) NSLog(@"%s: %@",#BOOLVARIABLE, BOOLVARIABLE ? @"YES" : @"NO" ) BOOL success = NO; LogBool(success); // Prints out 'success: NO' to the console success = YES; LogBool(success); // Prints out 'success: YES' to the console 

苹果的FixIt提供了%hhd,这正确地给了我BOOL的价值。

我们可以通过四种方式来检查

第一种方法是

 BOOL flagWayOne = TRUE; NSLog(@"The flagWayOne result is - %@",flagWayOne ? @"TRUE":@"FALSE"); 

第二种方法是

 BOOL flagWayTwo = YES; NSLog(@"The flagWayTwo result is - %@",flagWayTwo ? @"YES":@"NO"); 

第三种方法是

 BOOL flagWayThree = 1; NSLog(@"The flagWayThree result is - %d",flagWayThree ? 1:0); 

第四种方法是

 BOOL flagWayFour = FALSE; // You can set YES or NO here.Because TRUE = YES,FALSE = NO and also 1 is equal to YES,TRUE and 0 is equal to FALSE,NO whatever you want set here. NSLog(@"The flagWayFour result is - %s",flagWayFour ? YES:NO); 
 NSArray *array1 = [NSArray arrayWithObjects:@"todd1", @"todd2", @"todd3", nil]; bool objectMembership = [array1 containsObject:@"todd1"]; NSLog(@"%d",objectMembership); // prints 1 or 0 

这里是你如何做到这一点:

 BOOL flag = NO; NSLog(flag ? @"YES" : @"NO"); 
 //assuming b is BOOL. ternary operator helps us in any language. NSLog(@"result is :%@",((b==YES)?@"YES":@"NO"));