enumstypedefnsnumbernsintegernsuinteger

How to convert typedef enum to NSNumber?


  1. Is each value of a typedef enum treated as an int?

    E.g., given the following typedef enum:

    // UIView.h
    
    typedef enum {
        UIViewAnimationCurveEaseInOut,
        UIViewAnimationCurveEaseIn,
        UIViewAnimationCurveEaseOut,
        UIViewAnimationCurveLinear
    } UIViewAnimationCurve;
    

    How do I know which method to use to create an NSNumber?

    + (NSNumber *)numberWithShort:(short)value;
    + (NSNumber *)numberWithUnsignedShort:(unsigned short)value;
    + (NSNumber *)numberWithInt:(int)value;
    + (NSNumber *)numberWithUnsignedInt:(unsigned int)value;
    + (NSNumber *)numberWithLong:(long)value;
    + (NSNumber *)numberWithUnsignedLong:(unsigned long)value;
    + (NSNumber *)numberWithLongLong:(long long)value;
    + (NSNumber *)numberWithUnsignedLongLong:(unsigned long long)value;
    + (NSNumber *)numberWithInteger:(NSInteger)value NS_AVAILABLE(10_5, 2_0);
    + (NSNumber *)numberWithUnsignedInteger:(NSUInteger)value NS_AVAILABLE(10_5, 2_0);
    

    I think +[NSNumber numberWithInt:] is the correct method to use because the accepted answer to Best way to implement Enums with Core Data uses it. E.g.:

    [NSNumber numberWithInt:UIViewAnimationCurveLinear]
    

    But, if +[NSNumber numberWithInt:] is correct, then why?

  2. For a bitwise enum, e.g.:

    enum {
        UIViewAutoresizingNone                 = 0,
        UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,
        UIViewAutoresizingFlexibleWidth        = 1 << 1,
        UIViewAutoresizingFlexibleRightMargin  = 1 << 2,
        UIViewAutoresizingFlexibleTopMargin    = 1 << 3,
        UIViewAutoresizingFlexibleHeight       = 1 << 4,
        UIViewAutoresizingFlexibleBottomMargin = 1 << 5
    };
    typedef NSUInteger UIViewAutoresizing;
    

    I'm guessing that +[NSNumber numberWithUnsignedInteger:] is the correct method to use because there is an explicit NSUInteger after typedef. Correct? E.g.:

    [NSNumber numberWithUnsignedInteger:UIViewAutoresizingNone]
    

Solution

  • Nowadays modern syntax can be used:

    @(UIViewAnimationCurveLinear)