在Objective-C,安全性好办法比较2 BOOL值? [英] In Objective-c, safe and good way to compare 2 BOOL values?

查看:134
本文介绍了在Objective-C,安全性好办法比较2 BOOL值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Objective-C的比较2 BOOL值。

我发现(3) - (6)以下的code ++工程的结果。
(1) - (2)不起作用,因为BOOL就是符号字符

(3)的作品,是非常可读的,但我认为布尔不是目标c。结果
使用布尔在Objective-C code是好?

这是比较在Objective-C?结果2 BOOL值安全性好办法
是否有其他更好的方法来比较?

  BOOL B = YES;
BOOL C = 2;的NSLog(@(1)%D,B == C); // 不行
的NSLog(@(2)%D(BOOL)b ==(BOOL)C); // 不行
的NSLog(@(3)%D(布尔)b ==(布尔)C);
的NSLog(!@(4)%D,B ==!C);
的NSLog(@(5)%D,!! b ==!C);
的NSLog(@(6)%D,(B = 0)==(C = 0)!);

结果:

 (1)0
(2)0
(3)1
(4)1
(5)1
(6)1


解决方案

这是完全有效的使用布尔在Objective-C,因为它是C99标准的一部分(§7.16 )。在我看来,这也是处理布尔类型的比较安全的最佳方式。

的唯一理由不使用布尔到处是 BOOL 是在Objective-C全present和框架。

I want to compare 2 BOOL values in objective-c.

I found out that (3)-(6) of the following code works.
(1)-(2) doesn't work because BOOL is just signed char.

(3) works and is very readable but I think bool isn't objective-c.
Using bool in objective-c code is good?

Which is the safe and good way to compare 2 BOOL values in objective-c?
Are there other better ways to compare?

BOOL b = YES;
BOOL c = 2;

NSLog(@"(1) %d", b == c); // not work
NSLog(@"(2) %d", (BOOL)b == (BOOL)c); // not work
NSLog(@"(3) %d", (bool)b == (bool)c);
NSLog(@"(4) %d", !b == !c);
NSLog(@"(5) %d", !!b == !!c);
NSLog(@"(6) %d", (b != 0) == (c != 0));

results:

(1) 0
(2) 0
(3) 1
(4) 1
(5) 1
(6) 1

解决方案

It's perfectly valid to use bool in Objective-C as it's part of the C99 standard (§7.16). In my opinion it's also the best way to handle safe comparisons of boolean types.

The only reason not to use bool everywhere is that BOOL is omnipresent in Objective-C and the frameworks.

这篇关于在Objective-C,安全性好办法比较2 BOOL值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆