In Objective-c, safe and good way to compare 2 BOOL values?(在 Objective-c 中,比较 2 个 BOOL 值的安全和好方法?)
问题描述
我想比较 Objective-c 中的 2 个 BOOL 值.
I want to compare 2 BOOL values in objective-c.
我发现以下代码中的 (3)-(6) 有效.
(1)-(2) 不起作用,因为 BOOL 只是 signed char.
I found out that (3)-(6) of the following code works.
(1)-(2) doesn't work because BOOL is just signed char.
(3) 有效且可读性强,但我认为 bool 不是 Objective-c.
在objective-c代码中使用bool好不好?
(3) works and is very readable but I think bool isn't objective-c.
Using bool in objective-c code is good?
在 Objective-c 中比较 2 个 BOOL 值的安全和好方法是什么?
还有其他更好的比较方法吗?
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));
结果:
(1) 0
(2) 0
(3) 1
(4) 1
(5) 1
(6) 1
推荐答案
在 Objective-C 中使用 bool 是完全有效的,因为它是 C99 标准的一部分(第 7.16 节).在我看来,这也是处理布尔类型安全比较的最佳方式.
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.
不到处使用 bool 的唯一原因是 BOOL 在 Objective-C 和框架中无处不在.
The only reason not to use bool everywhere is that BOOL is omnipresent in Objective-C and the frameworks.
这篇关于在 Objective-c 中,比较 2 个 BOOL 值的安全和好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Objective-c 中,比较 2 个 BOOL 值的安全和好方法?
基础教程推荐
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
