将 Objective-C typedef 转换为其等效字符串
假设我在 .h 文件中声明了一个 typedef,如下所示:
typedef enum {
JSON,
XML,
Atom,
RSS
} FormatType;
我想构建一个将 typedef 的数值转换为字符串的函数。 例如,如果发送消息[self toString:JSON]
; 它将返回“JSON”。
该函数看起来像这样:
-(NSString *) toString:(FormatType)formatType {
//need help here
return [];
}
顺便说一句,如果我尝试使用此语法
[self toString:FormatType.JSON];
将 typedef 值传递给该方法,则会收到错误。 我缺少什么?
Assuming that I have a typedef declared in my .h file as such:
typedef enum {
JSON,
XML,
Atom,
RSS
} FormatType;
I would like to build a function that converts the numeric value of the typedef to a string. For example, if the message [self toString:JSON]
was sent; it would return 'JSON'.
The function would look something like this:
-(NSString *) toString:(FormatType)formatType {
//need help here
return [];
}
Incidentally, if I try this syntax
[self toString:FormatType.JSON];
to pass the typedef value to the method, I get an error. What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(22)
我的解决方案:
编辑:我在最后添加了更好的解决方案,使用 Modern Obj-C
1.
将名称作为键放入数组中。
确保索引是适当的枚举,并且顺序正确(否则例外)。
注意:names 是一个合成为 *_names* 的属性;
未检查代码的编译情况,但我在我的应用程序中使用了相同的技术。
//
2.
使用现代 Obj-C,我们可以使用字典将描述与枚举中的键联系起来。
顺序并不重要。
用法(在类实例方法中):
My solution:
edit: I've added even a better solution at the end, using Modern Obj-C
1.
Put names as keys in an array.
Make sure the indexes are the appropriate enums, and in the right order (otherwise exception).
note: names is a property synthesized as *_names*;
code was not checked for compilation, but I used the same technique in my app.
//
2.
Using Modern Obj-C you we can use a dictionary to tie descriptions to keys in the enum.
Order DOES NOT matter.
Usage (in a class instance method):
结合 @AdamRosenfield 答案、@Christoph 评论和另一个处理普通 C 枚举的技巧,我建议:
在最坏的情况下 - 比如如果你更改枚举但忘记更改名称数组 - 它将为此键返回 nil 。
Combining @AdamRosenfield answer, @Christoph comment and another trick to handle plain C enums I suggest:
In the worst case - like if you change the enum but forget to change the names array - it will return nil for this key.
在类头中定义 typedef 枚举:
在类中编写这样的方法:
将字符串放在 Localized.strings 文件中:
define typedef enum in class header:
write a method like this in class:
have the strings inside Localizable.strings file:
我将使用编译器的 # string 标记(以及宏以使其更加紧凑):
I would use the compiler's # string token (along with macros to make it all more compact):
我喜欢
#define
的做法:// 将其放入 .h 文件中,@interface 块之外
来源(来源不再可用)I like the
#define
way of doing this:// Place this in your .h file, outside the @interface block
source(source no longer available)我混合了此页面上找到的所有解决方案来创建我的解决方案,它是一种面向对象的枚举扩展或
某物。
事实上,如果您需要的不仅仅是常量(即整数),您可能需要一个模型对象(我们都在谈论 MVC,对吧?)
在使用它之前先问自己这个问题,我是对的,不是吗?事实上,需要一个真正的模型对象,从 webservice、plist、SQLite 数据库或 CoreData 初始化吗?
无论如何,这里是代码(MPI 代表“我的项目缩写”,似乎每个人都使用这个或他们的名字):
MyWonderfulType.h
:和
MyWonderfulType.m
:I made a sort of mix of all solutions found on this page to create mine, it's a kind of object oriented enum extension or
something.
In fact if you need more than just constants (i.e. integers), you probably need a model object (We're all talking about MVC, right?)
Just ask yourself the question before using this, am I right, don't you, in fact, need a real model object, initialized from a webservice, a plist, an SQLite database or CoreData ?
Anyway here comes the code (MPI is for "My Project Initials", everybody use this or their name, it seems) :
MyWonderfulType.h
:And
MyWonderfulType.m
:另一个解决方案:
在您的方法中您可以使用:
Another solution:
In your method you can use:
通过删除字符串依赖项改进了 @yar1vn 答案:
因此,当您更改枚举条目名称时,相应的字符串将被更改。
如果您不打算向用户显示此字符串,则很有用。
Improved @yar1vn answer by dropping string dependency:
Thus when you'll change enum entry name corresponding string will be changed.
Useful in case if you are not going to show this string to user.
@pixel在这里添加了最精彩的答案:
https://stackoverflow.com/a/24255387/1364257
请大家为他点赞吧!
他使用 20 世纪 60 年代简洁的 X 宏。 (我为现代 ObjC 稍微更改了他的代码)
就是这样。 干净整洁。
感谢@pixel! https://stackoverflow.com/users/21804/pixel
@pixel added the most brilliant answer here:
https://stackoverflow.com/a/24255387/1364257
Please, upvote him!
He uses the neat X macro from the 1960's. (I've changed his code a bit for the modern ObjC)
That's it. Clean and neat.
Thanks to @pixel! https://stackoverflow.com/users/21804/pixel
给定一个枚举定义,例如:
我们可以定义一个宏来将枚举值转换为其相应的字符串,如下所示。
块中使用的
switch
语句用于类型检查,也是为了获得 Xcode 中的自动完成支持。Given an enum definition like:
We can define a macro to convert an enum value to its corresponding string, as shown below.
The
switch
statement used in the block is for type checking, and also to get the auto-complete support in Xcode.我有一个大型枚举类型,我想将其转换为 NSDictionary 查找。 我最终从 OSX 终端使用
sed
作为:它可以读作:'捕获行上的第一个单词并输出 @(word) : @"word",'
这个正则表达式将枚举转换为名为“ObservationType.h”的头文件,其中包含:
到类似:
然后可以使用现代 Objective-C 语法
@{ }
(如上面 @yar1vn 所解释)将其包装在方法中以创建NSDictionary 查找:dispatch_once 样板只是为了确保静态变量以线程安全的方式初始化。
注意:我发现 OSX 上的 sed 正则表达式很奇怪 - 当我尝试使用
+
来匹配“一个或多个”时,它不起作用,不得不求助于使用{1,}
作为替代品I had a large enumerated type I wanted to convert it into an
NSDictionary
lookup. I ended up usingsed
from OSX terminal as:which can be read as: 'capture the first word on the line and output @(word) : @"word",'
This regex converts the enum in a header file named 'ObservationType.h' which contains:
into something like:
which can then be wrapped in a method using modern objective-c syntax
@{ }
(as explained by @yar1vn above) to create aNSDictionary
lookup :The
dispatch_once
boiler-plate is just to ensure that the static variable is initialised in a thread-safe manner.Note: I found the sed regex expression on OSX odd - when I tried to use
+
to match 'one or more' it didn't work and had to resort to using{1,}
as a replacement我使用 Barry Walk 答案的变体,按重要性顺序:
例如:
I use a variation on Barry Walk's answer, that in order of importance:
EG:
我在这里结合了几种方法。
我喜欢预处理器和索引列表的想法。
没有额外的动态分配,并且由于内联,编译器可能能够优化查找。
I combined several approaches here.
I like the idea of the preprocessor and the indexed list.
There's no extra dynamic allocation, and because of the inlining the compiler might be able to optimize the lookup.
首先,关于FormatType.JSON:JSON不是FormatType的成员,它是该类型的可能值。 FormatType 甚至不是复合类型 — 它是标量。
其次,执行此操作的唯一方法是创建映射表。 在 Objective-C 中,更常见的方法是创建一系列引用“符号”的常量,因此您将拥有
NSString *FormatTypeJSON = @"JSON"
等等。First of all, with regards to FormatType.JSON: JSON is not a member of FormatType, it's a possible value of the type. FormatType isn't even a composite type — it's a scalar.
Second, the only way to do this is to create a mapping table. The more common way to do this in Objective-C is to create a series of constants referring to your "symbols", so you'd have
NSString *FormatTypeJSON = @"JSON"
and so on.下面提供了一个解决方案,添加一个新的枚举需要
仅一行编辑,与在枚举 {} 列表中添加一行类似。
the following provides a solution such that to add a new enum requires
only a one-line edit, similar work to adding a single line in an enum {} list.
这里的每个答案基本上都说同样的事情,创建一个常规枚举,然后使用自定义 getter 在字符串之间切换。
我采用了一个更简单的解决方案,更快、更短、更干净 - 使用宏!
然后您只需开始输入
kNam...
,自动完成功能就会显示您想要的列表!此外,如果您想一次处理所有名称的逻辑,您可以简单地按顺序快速枚举文字数组,如下所示:
for (NSString *kName in kNames_allNames) {}
最后,NSString 转换在宏中确保行为类似于 typedef!
享受!
Every answer here basically says the same thing, create a regular enum and then use a custom getter to switch between strings.
I employ a much simpler solution that is faster, shorter, and cleaner—using Macros!
Then you can simply start to type
kNam...
and autocomplete will display the lists you desire!Additionally, if you want to handle logic for all the names at once you can simply fast enumerate the literal array in order, as follows:
for (NSString *kName in kNames_allNames) {}
Lastly, the NSString casting in the macros ensures behavior similar to typedef!
Enjoy!
我想我刚刚创建了最优雅的方法来解决这个问题。
(受到 @AdamRosenfield 的启发)
例如,您可以像这样声明枚举:
然后,您将获得两个函数在枚举和字符串之间进行转换:
是不是很酷? 以下是神奇的宏:
I think I just created the most elegant approach to solve this.
(inspired by @AdamRosenfield)
For example, you may declare the enum like this:
Then, you get the two functions to convert between enums and strings:
Is that cool? Here are the magic macros:
很多答案都还不错。
如果您正在寻找使用一些宏的通用 Objective C 解决方案...
关键功能是它使用枚举作为 NSString 常量静态数组的索引。
数组本身被包装到一个函数中,使其更像 Apple API 中流行的 NSStringFromXXX 函数套件。
您需要在此处找到
#import "NSStringFromEnum.h"
http://pastebin.com/u83RR3Vk
[编辑]
还需要在这里找到
#import "SW+Variadic.h"
http://pastebin.com/UEqTzYLf示例 1:使用字符串转换器完全定义一个新的枚举 typedef。
在 myfile.h
中的 myfile.m 中:
使用:
NSStringFromEnumDispatch_chain_cmd(chain_for_c)
返回@"chain_for_c"
enumDispatch_chain_cmdFromNSString(@"chain_previous")
返回chain_previous
示例 2:为现有枚举提供转换例程
还演示了如何使用设置字符串以及重命名函数中使用的类型名。
在 myfile.h
在 myfile.m 中:
Many answers all fairly good.
If you are after a generic, Objective C solution that uses some macros...
Key feature is it uses the enum as an index into a static array of NSString constants.
the array itself is wrapped into a function to make it more like the suite of NSStringFromXXX functions prevalent in the Apple APIs.
you will need to
#import "NSStringFromEnum.h"
found herehttp://pastebin.com/u83RR3Vk
[EDIT]
also needs
#import "SW+Variadic.h"
found here http://pastebin.com/UEqTzYLfExample 1 : completely define a NEW enum typedef, with string converters.
in myfile.h
in myfile.m:
to use :
NSStringFromEnumDispatch_chain_cmd(chain_for_c)
returns@"chain_for_c"
enumDispatch_chain_cmdFromNSString(@"chain_previous")
returnschain_previous
Example 2: provide conversion routines for an existing enum
also demonstrates using a settings string, and renaming the typename used in the functions.
in myfile.h
in myfile.m:
这是工作 -> https://github.com/ndpiparava/ObjcEnumString
Here is working -> https://github.com/ndpiparava/ObjcEnumString
根据您的需要,您也可以使用编译器指令来模拟您正在寻找的行为。
只需记住通常的编译器缺点即可,(类型不安全,直接复制粘贴会使源文件更大)
Depending on your needs, you could alternatively use compiler directives to simulate the behaviour you are looking for.
Just remember the usual compiler shortcomings, (not type safe, direct copy-paste makes source file larger)
这实际上是一个 C 问题,并非特定于 Objective-C(它是 C 语言的超集)。 C 中的枚举表示为整数。 因此,您需要编写一个函数,返回给定枚举值的字符串。 有很多方法可以做到这一点。 一个字符串数组,这样枚举值可以用作数组的索引或将枚举值映射到字符串的映射结构(例如
NSDictionary
),但我发现这些方法不如使转换显式的函数清晰(以及数组方法,尽管如果您的枚举值不从 0 连续,经典的 C 方法是危险的)。 像这样的事情会起作用:关于枚举值的正确语法的相关问题是您仅使用该值(例如
JSON
),而不是FormatType.JSON
语法。FormatType
是一种类型,枚举值(例如JSON
、XML
等)是您可以分配给该类型的值。This is really a C question, not specific to Objective-C (which is a superset of the C language). Enums in C are represented as integers. So you need to write a function that returns a string given an enum value. There are many ways to do this. An array of strings such that the enum value can be used as an index into the array or a map structure (e.g. an
NSDictionary
) that maps an enum value to a string work, but I find that these approaches are not as clear as a function that makes the conversion explicit (and the array approach, although the classicC
way is dangerous if your enum values are not continguous from 0). Something like this would work:Your related question about the correct syntax for an enum value is that you use just the value (e.g.
JSON
), not theFormatType.JSON
sytax.FormatType
is a type and the enum values (e.g.JSON
,XML
, etc.) are values that you can assign to that type.你不能轻易做到。 在 C 和 Objective-C 中,枚举实际上只是美化的整数常量。 您必须自己生成一个名称表(或者滥用一些预处理器)。 例如:
这种方法的危险在于,如果您更改了枚举,则必须记住更改名称数组。 您可以通过滥用一些预处理器来解决这个问题,但它很棘手且丑陋。
另请注意,这假设您有一个有效的枚举常量。 如果您有来自不受信任来源的整数值,则还需要检查常量是否有效,例如,通过在枚举中包含“过去的最大值”值,或者检查它是否小于数组长度,
sizeof(FormatType_toString) / sizeof(FormatType_toString[0])
。You can't do it easily. In C and Objective-C, enums are really just glorified integer constants. You'll have to generate a table of names yourself (or with some preprocessor abuse). For example:
The danger of this approach is that if you ever change the enum, you have to remember to change the array of names. You can solve this problem with some preprocessor abuse, but it's tricky and ugly.
Also note that this assumes you have a valid enum constant. If you have an integer value from an untrusted source, you additionally need to do a check that your constant is valid, e.g. by including a "past max" value in your enum, or by checking if it's less than the array length,
sizeof(FormatType_toString) / sizeof(FormatType_toString[0])
.