【发布时间】:2011-08-16 00:40:44
【问题描述】:
如果我有以下枚举类型:
typedef enum {Type1=0, Type2, Type3} EnumType;
下面的代码(如果转换成 Java 就可以正常工作):
NSArray *allTypes = [NSArray arrayWithObjects:[NSNumber numberWithInt:Type1], [NSNumber numberWithInt:Type2], [NSNumber numberWithInt:Type3], nil];
EnumType aType = -1;
NSLog(@"aType is %d", aType); // I expect -1
// Trying to assign the highest type in the array to aType
for (NSNumber *typeNum in allTypes) {
EnumType type = [typeNum intValue];
NSLog(@"type is: %d", type);
if (type > aType) {
aType = type;
}
}
NSLog(@"aType is %d", aType); // I expect 2
生成的日志是:
TestEnums[11461:b303] aType is: -1
TestEnums[11461:b303] type is: 0
TestEnums[11461:b303] type is: 1
TestEnums[11461:b303] type is: 2
TestEnums[11461:b303] aType is: -1
当我使用断点检查 aType 的值时,我看到:
aType = (EnumType) 4294967295
according to Wikipedia 是 32 位系统的最大 unsigned long int 值。
这是否意味着我不能为非枚举类型赋值 在类型值的有效范围内?
为什么log(-1)的值与真实值不同 (4294967295)?和说明符(%d)有关系吗?
如何在不添加新内容的情况下实现我在此处尝试执行的操作 类型来表示无效值?请注意,该集合可能 有时是空的,这就是为什么我在开头使用 -1 表示如果集合为空则没有类型。
注意:我是 Objective-C/ANSI-C 的新手。
谢谢, 莫塔
编辑:
这是我发现的一些奇怪的东西。如果我将循环内的条件更改为:
if (type > aType || aType == -1)
我得到以下日志:
TestEnums[1980:b303] aType is -1
TestEnums[1980:b303] type is: 0
TestEnums[1980:b303] type is: 1
TestEnums[1980:b303] type is: 2
TestEnums[1980:b303] aType is 2
这正是我要找的!奇怪的部分是 (aType == -1) 是真的,而 (Type1 > -1)、(Type2 > -1) 和 (Type3 > -1) 不是?!
【问题讨论】:
标签: objective-c enums