简体   繁体   English

新的现代Objective-C枚举类型检查

[英]New modern Objective-C enum type check

If I declare enum type with new NS_ENUM macro which was introduced because of stronger type check, am I able to check for this type also in runtime? 如果我使用由于更强类型检查而引入的新NS_ENUM宏声明枚举类型,我是否也能在运行时检查此类型?

I mean, I have 我的意思是,我有

typedef NS_ENUM(NSUInteger, MyNewType) {

    MyNewTypeInstance1,
    MyNewTypeInstance2,
    MyNewTypeInstance3

};

. And I want to know that for example (NSUInteger)i = 2 is kind of MyNewType . 我想知道例如(NSUInteger)i = 2MyNewType一种。

No. NS_ENUM is just a way of using a feature introduced to Objective-C via C++11 called "fixed underlying types" for enumerations. 不, NS_ENUM只是一种使用通过C ++ 11引入Objective-C的功能的方法,称为“固定底层类型”用于枚举。 This ensures that the type used to store the enumerated values is of a fixed size and signedness, but it doesn't allow you to inquire about the enumerated type at runtime. 这可确保用于存储枚举值的类型具有固定大小和签名,但它不允许您在运行时查询枚举类型。

If you're interested in validating whether values are actually members of your enumeration, there are two related approaches for that. 如果您有兴趣验证值是否实际是枚举的成员,则有两种相关的方法。 If the values are contiguous, you can write a macro that checks whether the value in question is in the valid contiguous range. 如果值是连续的,则可以编写一个宏来检查有问题的值是否在有效的连续范围内。 Otherwise, you can take the more general (and verbose) approach that Apple takes with, eg UIDeviceOrientationIsValidInterfaceOrientation , and explicitly check against all valid enumerated values. 否则,您可以采用Apple采用的更通用(和详细)的方法,例如UIDeviceOrientationIsValidInterfaceOrientation ,并显式检查所有有效的枚举值。

@warrenm: good ansewr @warrenm:好的ansewr

i was thinking about this: 我在想这个:

what about adding a sort of "myLastValueJustToCheck" and check if your int is < that value? 怎么样添加一个“myLastValueJustToCheck”并检查你的int是否<那个值?

typedef NS_ENUM(NSUInteger, MyNewType) {
    MyNewTypeInstance1,
    MyNewTypeInstance2,
    MyNewTypeInstance3,
    myLastValueJustToCheck
};

then check: 然后检查:

NSUInteger i = 2;
NSLog(@"is %i i in my range? %i", i, (i<myLastValueJustToCheck));

i = 3;
NSLog(@"is %i i in my range? %i", i, (i<myLastValueJustToCheck));

i = 4;
NSLog(@"is %i i in my range? %i", i, (i<myLastValueJustToCheck));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM