如何在init方法中使用枚举?

时间:2014-02-03 00:38:21

标签: objective-c cocoa-touch enums initialization

我有以下代码,它有一个init方法,它将枚举作为一个属性,但我收到一个选定标识符的错误。

typedef NS_ENUM(NSUInteger, ActivtyLevel) {
    kActivityLevelSedentary,
    kActivityLevelLight,
    kActivityLevelModerate,
    kActivityLevelHeavy,
    kActivityLevelExtreme
};

@interface DFUserProfile ()

@property (nonatomic, strong) NSNumber *weight;
@property (nonatomic, strong) NSNumber *bodyFatPercentage;

@end

@implementation DFUserProfile

- (id)initWithWeight:(NSNumber *)iWeight bodyFat:(NSNumber *)iBodyFat andActivityLevel:(NSUInteger)iActivtyLevel {
    if (self = [super init]) {
        _weight = iWeight;
        _bodyFatPercentage = iBodyFat;
        ActivtyLevel = iActivtyLevel;
    }

    return self;
}

@end

2 个答案:

答案 0 :(得分:2)

typedef声明名为ActivityLevel类型,您需要具有该类型的变量属性

例如,您可以声明属性:

@property (nonatomic) ActivityLevel activityLevel;

然后将您的方法声明为:

- (id)initWithWeight:(NSNumber *)iWeight
             bodyFat:(NSNumber *)iBodyFat
    andActivityLevel:(ActivityLevel)iActivtyLevel // note use of the enumeration type
{
    ...

    _activityLevel = iActivityLevel;

答案 1 :(得分:1)

你需要有一个枚举类型的变量,你不能将它直接存储到枚举中,即一个类型。加上这个:

@property (nonatomic) ActivityLevel activityLevel;

然后在你的init方法中:

_activtyLevel = iActivtyLevel;