如果我有以下枚举类型:
typedef enum {Type1=0, Type2, Type3} EnumType;
Run Code Online (Sandbox Code Playgroud)
以下代码(如果转换为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
Run Code Online (Sandbox Code Playgroud)
生成的日志是:
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
Run Code Online (Sandbox Code Playgroud)
当我使用断点检查aType的值时,我看到:
aType = (EnumType) 4294967295
Run Code Online (Sandbox Code Playgroud)
这是根据维基百科用于32位系统中的最大无符号长int值.
这是否意味着我无法为不在类型值的有效范围内的枚举类型赋值?
为什么log(-1)的值与实际值(4294967295)不同?它与说明符(%d)有关吗?
如何在不添加新类型来表示无效值的情况下实现此操作?请注意,该集合有时可能为空,这就是为什么我在开头使用-1表示如果集合为空则没有类型.
注意:我是Objective-C/ANSI-C的新手.
谢谢,莫塔
编辑:
这是我发现的奇怪之处.如果我将循环内的条件更改为:
if (type > aType || aType == -1)
Run Code Online (Sandbox Code Playgroud)
我得到以下日志:
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
Run Code Online (Sandbox Code Playgroud)
这正是我正在寻找的!怪异的部分是如何(aType == -1)为真,而(Type1> -1),(Type2> -1)和(Type3> -1)不是?!
似乎EnumType被定义为一种unsigned类型.分配给它时-1,该值实际上回滚到无符号32位整数的最大可能值(如您所见).因此,通过启动值at -1,您确保没有其他值与您进行比较可能更高,因为它被分配给数据类型(4294967295)的最大值.
我建议只是启动计数器0,因为它是一个最低的值EnumType.
EnumType aType = 0;
Run Code Online (Sandbox Code Playgroud)
如果要检查是否选择了任何值,可以检查count集合中的值以查看是否存在任何值.
| 归档时间: |
|
| 查看次数: |
1352 次 |
| 最近记录: |