Objective-C 枚举重定义错误

7
typedef enum {
    artists = 0,
    artists_songs = 1,
    artist_albums = 2,
    albums = 3,
    album_songs = 4,
    tags = 5,
    tag = 6,
    tag_artists = 7,
    tag_albums = 8,
    tag_songs = 9,
    songs = 10,
    song = 11,
    playlists = 12,
    playlist = 13,
    playlist_songs = 14,
    search_songs = 15
} Methods;

typedef enum {
    artists = 0,
    albums = 1,
    songs = 2,
    tags = 3,
    playlists = 4    
} ReturnTypes;

我在ReturnTypes的artists = 0这一行上不断收到错误提示,说artists已经被重新声明了。我不确定这个语法错误是什么。有什么想法吗?


从任何一个枚举定义中删除 artists,因为它在您的应用程序中声明了重复的 artist 常量。 - Dipen Panchasara
3个回答

16
语法错误是 artists 被重新声明了!你已经在第一个枚举中声明了它,现在你又试图在第二行中声明它。这些枚举不是单独的类型,它们只是常量列表。你不能有两个被称为 artists 的常量。
这就是为什么 Cocoa 中的枚举有着非常冗长乏味的名称,例如 UITableViewCellStyleDefault。这是为了避免它们彼此冲突。你应该做同样的事情,比如使用 MyMethodsArtistsMyReturnTypesArtists

1
哇,Obj-C 不区分吗?我不能像 Methods.artists 或 ReturnTypes.artists 这样做吗? - Ryan Copley
NS_ENUM 宏是 LLVM 4.0 中新增的,它在某种程度上改善了一些问题,使得编译器能够在枚举类型上进行类似于类型检查的操作,但是全局命名空间问题仍然存在。 - matt
@RyanCopley:不幸的是,C语言没有命名空间。通常的解决方法是在标识符上使用前缀(例如return_artistsrt_artists)。 - Chuck

0
一个enum只是整数常量的语法糖。你不能在多个地方定义相同的标识符;在这种情况下,你试图在多个枚举中使用相同的名称。
你可以尝试使用带有静态成员的类(粗略示例,未经测试的代码):
@implementation MethodsEnum

+(int)artists
{
    return 0;
}

+(int)artists_songs
{
    return 1;
}

// etc.

@end

@implementation ReturnTypeEnum

+(int)artists
{
    return 0;
}

+(int)albums
{
    return 1;
}

// etc.

@end

请注意,我并不推荐这种方法,但它模拟了一些你从Java的“枚举”中似乎缺少的语言特性。

0
你的枚举类型中都有"artists"。编译器并不关心它们是否具有相同的值,它会抛出一个错误。
尝试重新定义其中一个。对于所有其他被重新定义的常量,你将遇到同样的问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接