Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store enums in an NSArray?

I'm new to Objective-C, but experienced in C++ and C.

I want to store some enum constants in an array. In C++ I would do something like this:

enum color {RED, BLUE, YELLOW, GREEN};
vector<color> supportedColors;
supportedColors.push_back(RED);
supportedColors.push_back(GREEN);

But the NSArray will only store object pointers (id's). So how should they be stored? I could possibly cast them to integers and store them in an NSNumber object, but this seems messy.

I wonder what experienced obj-c programmers do?

like image 817
joerick Avatar asked Jul 03 '10 16:07

joerick


2 Answers

Cast them to integers and store them in NSNumbers. :)

Native C types are really second class citizens in the Cocoa collection classes, and are often verbose to work with if you want to intermingle. C says that enums have integral values, so it's safe to use them as ints in this way.

Depending on what you're doing of course, you can simplify the manipulation code by wrapping that enum in an actual object ("MyColor") that has the enum as a property on it. These objects could then be tossed around in the collection classes as desired, with some upfront and runtime overhead that are unlikely to matter from a perf standpoint, depending on what you're doing.

like image 145
Ben Zotto Avatar answered Nov 04 '22 12:11

Ben Zotto


You are perhaps looking for a way to simply loop through all of the options? How about just a plan old normal array?

typedef enum {RED,BLUE,GREEN,YELLOW} color;

color colors[4]={RED,YELLOW,GREEN,BLUE};
for (int i=0;i<4;i++)
    colors[i];

On the other hand if performance isn't an issue and you are just looking to clean up the code a little; how about creating a class ColorArray that encapsulates NSMutableArray and creates the relevant methods.

ColorArray.h:

#import <Foundation/Foundation.h>

typedef enum {RED,BLUE,GREEN,YELLOW} Color;

@interface ColorArray : NSObject {
    NSMutableArray* _array;
}

- (id) initWithArray:(Color[])colors;

- (void) addColor:(Color)color;
- (Color) colorAtIndex:(int)i;

@end

ColorArray.c:

#import "ColorArray.h"

@implementation ColorArray

- (id) init {
    if (self = [super init]) {
        _array = [[NSMutableArray alloc] init];
    }
    return self;
}
- (id) initWithArray:(Color[])colors {
    if (self = [super init]) {
        _array = [[NSMutableArray alloc] init];
        for (int i=0;colors[i]!=0;i++)
            [_array addObject:[NSNumber numberWithInt:colors[i]]];
    }
    return self;
}
- (void) dealloc {
    [_array release];
    [super dealloc];
}

- (void) addColor:(Color)color {
    [_array addObject:[NSNumber numberWithInt:color]];
}
- (Color) colorAtIndex:(int)i {
    return [[_array objectAtIndex:i] intValue];
}

@end
like image 37
aepryus Avatar answered Nov 04 '22 11:11

aepryus