【问题标题】:How To Compare Integer to Objective-C enum如何将整数与 Objective-C 枚举进行比较
【发布时间】:2014-11-10 15:25:18
【问题描述】:
- (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) {}

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

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

【问题讨论】:

    标签: objective-c macos cocoa enums


    【解决方案1】:

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

    所以你的if 应该是这样的:

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

    在您的 sn-p 中,您比较的是指针,而不是对象。

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

    i = ICScannerFunctionalUnitTypeDocumentFeeder
    

    【讨论】:

      【解决方案2】:

      您不能在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
      

      您的示例中似乎缺少此阶段。

      最后,将您的整数值与来自 enum 的值进行比较,无需引用 enum 名称,只需使用构成枚举的各个值即可:

      [[arrayTwo lastObject] integerValue] == ICScannerFunctionalUnitTypeFlatbed
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-28
        相关资源
        最近更新 更多