在 Objective-C 枚举中查找整数值
Objective-C 中是否可以查看 int
值是否在特定的 enum
中?例如,在此枚举中:
enum {
ValidationLoginFailed = 2000,
ValidationSessionTokenExpired = 2001,
ValidationSessionTokenInvalid = 2002,
ValidationEmailNotFound = 2003
};
typedef int ValidationStatusCodes;
是否可以查看 ValidationStatusCodes
enum
中是否存在任意整数值?
[ValidationStatusCodes contains:intResponseCode]
或者至少
[self intIsInRangeofEnum:ValidationStatusCodes forValue:intResponseCode]
Is it possible in Objective-C to see if a int
value is in a particular enum
? For instance, in this enum:
enum {
ValidationLoginFailed = 2000,
ValidationSessionTokenExpired = 2001,
ValidationSessionTokenInvalid = 2002,
ValidationEmailNotFound = 2003
};
typedef int ValidationStatusCodes;
is it possible to see if an arbitrary integer value is in the ValidationStatusCodes
enum
?
[ValidationStatusCodes contains:intResponseCode]
or at least
[self intIsInRangeofEnum:ValidationStatusCodes forValue:intResponseCode]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
没有比直接做更简单的方法了
。一般来说,C 对于做动态事情或反映类型没有太大帮助,而枚举是 C 的一项功能。
There's no simpler way than just doing
In general, C is not very helpful for doing dynamic things or reflecting on types, and enums are a C feature.
不使用
枚举
。enum
不是 Objective-C 对象,因此您无法像现在这样向它发送消息。也许使用 NSDictionary ?
Not with an
enum
. Anenum
is not an objective-C object, so you can't send it messages as you're doing.Maybe use an NSDictionary?
这个问题有点过时了,但我在软件设计中看到的标准是使用位掩码,其中每个值都是带有位移位的离散状态。在某些情况下,您的枚举值可以是其他值的组合。
对于您的用例,您将
&
包含集合中所有项目的结果:This question is a little dated, but the standard I have seen in software design is to use a bitmask where each of these values is a discrete state with a bit-shift. In some cases, your enum values can be combinations of other values.
For your use-case you would
&
your result with all of the items in the set:好吧,只要这个问题再提出来。有一个很好的开源项目 JREnum
它允许执行以下操作:
然后
ValidationStatusCodesByValue()
返回NSDictionary
,其键对应于NSNumber
。所以:Well, as long as this question is up again. There's a nice open source project JREnum
Which allows to do the following thing:
And then
ValidationStatusCodesByValue()
returnsNSDictionary
which keys are correspondingNSNumber
s. So:[更新]
在一些 C++ 帖子中发现了这个方法,虽然不是完全动态的,但可以用最小的麻烦完成这个技巧:
将范围范围添加到枚举条目:
然后沿着这些线进行操作:
显然最终的代码远不止这 4 个代码app 中也会出现相应的错误块。
[UPDATE]
Found this method in some C++ posts which, although not entirely dynamic, does the trick with minimal fuss:
Add range extents to enum entries:
then something along these lines:
obviously there are far more than just these 4 codes in the final app and there will a block of corresponding error ones too.