How to convert typedef enum to NSNumber?
Asked Answered
T

2

15
  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]
    
Tubb answered 21/4, 2012 at 0:35 Comment(0)
K
25

Nowadays modern syntax can be used:

@(UIViewAnimationCurveLinear)

Kingston answered 4/4, 2015 at 13:39 Comment(0)
P
8

[NSNumber numberWithInt:your_enum_int_variable];

Poltroon answered 13/12, 2012 at 0:31 Comment(1)
You rock! Thank for this.Devereux

© 2022 - 2024 — McMap. All rights reserved.