简体   繁体   中英

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?

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 .

No. NS_ENUM is just a way of using a feature introduced to Objective-C via C++11 called "fixed underlying types" for enumerations. 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.

@warrenm: good ansewr

i was thinking about this:

what about adding a sort of "myLastValueJustToCheck" and check if your int is < that value?

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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