Save listings in NSArray?

I am new to Objective-C but experienced in C ++ and C.

I want to save some enumeration 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 it NSArraywill store object pointers ( id's). So how to store them? I could cast them to integers and store them in an object NSNumber, but that seems messy.

I wonder what experienced obj-c programmers do?

+5
source share
3 answers

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

C Cocoa, , . C , , ints .

, , , ( "MyColor" ), . , , , , .

+13

enum,

vector<colorEnumClass> supportedColours

, : , , .. IF, . : -)

, supportedColours , , . , "" . Singleton, pushback() .., .

"" Java

, Objective C, . .

0

, ? ?

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 is not an issue and you just want to clear up the code a bit; how about creating a ColorArray class that encapsulates NSMutableArray and creates the appropriate 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
0
source

All Articles