将 NSString 转换为枚举的最佳方法
假设我定义了这个枚举(来自 Apple 的 UIKit 框架):
typedef enum {
UITextAutocorrectionTypeDefault,
UITextAutocorrectionTypeNo,
UITextAutocorrectionTypeYes,
} UITextAutocorrectionType;
并且我有一个带有“UITextAuto CorrectionTypeDefault”值的简单字符串。就我而言,该字符串来自 JSON 对象,但这并不重要。
将字符串转换为正确的枚举值以便我可以在类中设置属性的最佳方法是什么?我知道 Obj-C 不能直接转换值(就像使用 Java 或 C# 所做的那样),在我的例子中,我有很多枚举,以及可能稍后创建的枚举。除了必须手动创建映射字典之外,是否有任何自动或半自动方法可以执行此操作?
Lets say I have this enum defined (from Apple's UIKit framework):
typedef enum {
UITextAutocorrectionTypeDefault,
UITextAutocorrectionTypeNo,
UITextAutocorrectionTypeYes,
} UITextAutocorrectionType;
and I have a simple string with "UITextAutocorrectionTypeDefault" value. In my case, this string is coming from a JSON object, but it doesn't matter.
What would be the best way for me to convert the string into the proper enum value so I can set a property in the class? I know Obj-C can't just convert the value directly (like you can do with Java or C#), and in my case I have lots of enums, and ones that may be created at a later time. Are there any automatic or semi-automatic ways of doing this, other than having to create a mapping dictionary manually?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
C
(请阅读Objective-C
)中,除了手动映射值之外没有其他方法可以做到这一点。枚举仅定义常量值,这些常量值无法在运行时与字符串相互转换,就像在 C# 或 Java 中将它们视为对象一样。您可以在编译时字符串化这些值。
In
C
(readObjective-C
) there is no way to do this other than manually mapping the values. The enum just defines constant values that can not be converted to or from a string at runtime like they can inC#
orJava
which treats them as objects.You can how ever stringify the values at compile time.