如何将整数与Objective-C枚举类型进行比较

3
- (void)updateCheckBoxes {
    NSArray *availableFuncUnits = _scanner.availableFunctionalUnitTypes;
    for(int i = 0; i < [availableFuncUnits count]; i++) {

    }
}

如果我在for循环内设置一个断点,NSArray *'availableFuncUnits'的元素是(__NSCFNumber *)(int)0(__NSCFNumber *)(long)3

该数组应包含以下元素:

enum
{
    ICScannerFunctionalUnitTypeFlatbed              = 0,
    ICScannerFunctionalUnitTypePositiveTransparency = 1,
    ICScannerFunctionalUnitTypeNegativeTransparency = 2,
    ICScannerFunctionalUnitTypeDocumentFeeder       = 3
};
typedef NSUInteger ICScannerFunctionalUnitType; 

我应该能做以下事情吧?
if([availableFuncUnits objectAtIndex:i] == ICScannerFunctionalUnitType.ICScannerFunctionalUnitTypeDocumentFeeder) {}

但是它总是给我一个错误,说“预期的标识符或'('”。

我如何正确执行这个比较?非常感谢您的帮助!

2个回答

4

我看到两个问题:
1) 数组availableFuncUnits包含NSNumber对象。你不能直接将它们与原始类型(NSUInteger)进行比较。

所以你的if应该像这样:

ICScannerFunctionalUnitType type = [availableFuncUnits[i] integerValue]
if(type == ICScannerFunctionalUnitTypeDocumentFeeder){}

在您的代码片段中,您比较的是指针,而不是对象。

2)您看到的错误是因为使用枚举的正确方法是:

i = ICScannerFunctionalUnitTypeDocumentFeeder

1

你不能在NSArray中存储整数,因为数组只能包含对象。要将整数放入数组中,必须使用NSNumber进行包装:

NSInteger a = 100;
NSInteger b = 200;
NSInteger c = 300;

// Creating NSNumber objects the long way 
NSArray *arrayOne = [NSArray alloc] initWithObjects:[NSNumber numberWithInteger:a],
                                                    [NSNumber numberWithInteger:b],
                                                    [NSNumber numberWithInteger:c], nil];
// Creating NSNumber objects the short way
NSArray *arrayTwo = [[NSArray alloc] initWithObjects:@100, @200, @300, nil];

这与你的问题相关,因为当你从数组中提取NSNumber对象时,如果你想将它们与实际整数进行比较,你必须将它们转换回整数(解包)。
NSLog(@"%d", [arrayOne firstObject] == 100); // COMPILER WARNING!!!
NSLog(@"%d", [[arrayOne firstObject] integerValue] == 100); // True
NSLog(@"%d", [[arrayTwo lastObject] integerValue] == 200);  // False

这个示例中似乎缺少这个阶段。
最后,要将整数值与枚举类型中的值进行比较,无需引用枚举名称,只需使用组成枚举的单个值即可。
[[arrayTwo lastObject] integerValue] == ICScannerFunctionalUnitTypeFlatbed

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