Ios – Assign Enum to Variable in Objective-C

enumenumsiosobjective cruntime-error

How can I assign an to a variable and access its value later? I thought this would be pretty simple, but every time I try to assign the enum value to a variable (no type mismatches or warnings in Xcode appear) my app crashes with an EXC_BAD_ACCESS error.

Here's how I setup my enum in my header file (BarTypes.h):

typedef enum {
    BarStyleGlossy,
    BarStyleMatte,
    BarStyleFlat
} BarDisplayStyle;

No issues there (reading and using the values at least). However, when I create a variable that can store one of the enum values (BarStyleGlossy, BarStyleMatte, or BarStyleFlat) then try to set that variable, the app crashes. Here's how I setup and use the variable:

//Header
@property (nonatomic, assign, readwrite) BarDisplayStyle barViewDisplayStyle; //I've also tried just using (nonatomic) and I've also tried (nonatomic, assign)

//Implementation
@synthesize barViewDisplayStyle;

- (void)setupBarStyle:(BarDisplayStyle)displayStyle {
    //This is where it crashes:
    self.barViewDisplayStyle = displayStyle;
}

Why is it crashing here? How do I store the value of an enum in a variable? I think the issue has to do with a lack of understanding about enums on my end, however if I follow conventional variable setup and allocation, etc. this should work. Any ideas on what I'm doing wrong?

Please note that I'm new to enums, so my vocabulary here may be a bit mixed up (forgive me – and feel free to make an edit if you know what I'm trying to say).

I found a few references about enums across the web:

EDIT: Here's how I call the setupBarStyle method:

BarView *bar = [[BarView alloc] init];
[bar setupBarStyle:displayStyle];

Best Answer

Just in case anyone out there is still trying to figure out how to assign an enum value to an enum typed variable or property... Here is an example using a property.

In the header file...

@interface elmTaskMeasurement : NSObject

typedef NS_ENUM(NSInteger, MeasurementType) {
    D,
    N,
    T,
    Y,
    M
};

@property(nonatomic) MeasurementType MeasureType;

@end

In the file where the object is created...

elmTaskMeasurement *taskMeasurement = [[elmTaskMeasurement alloc] init];

taskMeasurement.MeasureType = (MeasurementType)N;