如何将typedef enum转换为NSNumber?

时间:2012-04-21 00:35:58

标签: enums typedef nsnumber nsinteger nsuinteger

  1. typedef enum的每个值都被视为int

    例如,给出以下typedef enum

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

    我如何知道使用哪种方法创建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);
    

    我认为+[NSNumber numberWithInt:]是正确的使用方法,因为accepted answer to Best way to implement Enums with Core Data使用它。 E.g:

    [NSNumber numberWithInt:UIViewAnimationCurveLinear]
    

    但是,如果+[NSNumber numberWithInt:]是正确的,那么为什么呢?

  2. 对于按位enum,例如:

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

    我猜测+[NSNumber numberWithUnsignedInteger:]是正确的使用方法,因为在NSUInteger之后有一个明确的typedef。正确? E.g:

    [NSNumber numberWithUnsignedInteger:UIViewAutoresizingNone]
    

2 个答案:

答案 0 :(得分:19)

现在可以使用现代语法:

@(UIViewAnimationCurveLinear)

答案 1 :(得分:7)

[NSNumber numberWithInt:your_enum_int_variable];