转换的Objective-C的typedef对应的字符串 [英] Convert objective-c typedef to its string equivalent

查看:201
本文介绍了转换的Objective-C的typedef对应的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在.h文件中这样声明一个typedef:

Assuming that I have a typedef declared in my .h file as such:

typedef enum {
  JSON,
  XML,
  Atom,
  RSS
} FormatType;

我想建立一个自定义类型的数值转换为字符串的函数。例如,如果消息 [个体经营的toString:JSON] 发送;它会返回JSON。

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];

到的typedef值传递给方法,我得到一个错误。我缺少什么?

to pass the typedef value to the method, I get an error. What am I missing?

推荐答案

这真是一个C的问题,而不是具体到Objective-C(这是C语言的超集)。用C枚举是psented为整数再$ P $。所以,你需要写一个返回给定一个枚举值的字符串的函数。有很多方法可以做到这一点。字符串,例如数组,枚举值可以用来作为索引到数组或地图结构(例如,一个的NSDictionary )的一个枚举值映射到一个字符串的工作,但我发现,这些方法都不能作为函数使转换明确(和数组的做法一样清晰,虽然经典 C 办法是危险的,如果你的枚举值不从0 continguous)。像这样将工作:

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 classic C way is dangerous if your enum values are not continguous from 0). Something like this would work:

- (NSString*)formatTypeToString:(FormatType)formatType {
    NSString *result = nil;

    switch(formatType) {
        case JSON:
            result = @"JSON";
            break;
        case XML:
            result = @"XML";
            break;
        case Atom:
            result = @"Atom";
            break;
        case RSS:
            result = @"RSS";
            break;
        default:
            [NSException raise:NSGenericException format:@"Unexpected FormatType."];
    }

    return result;
}

您了解的正确语法的枚举值相关的问题是,你只使用值(如 JSON ),而不是 FormatType.JSON 语法来。 FormatType 是一个类型和枚举值(例如: JSON XML 等)是可以分配给该类型的值。

Your related question about the correct syntax for an enum value is that you use just the value (e.g. JSON), not the FormatType.JSON sytax. FormatType is a type and the enum values (e.g. JSON, XML, etc.) are values that you can assign to that type.

这篇关于转换的Objective-C的typedef对应的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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