joec
joec

Reputation: 3543

Using named value from enum in Objective C

I have an enum defined as follows:

typedef enum modifiers {
                        modifierNone=-1,
                        modifierCmd,
                        modifierShift,
                        modifierOption
                        } Modifier;

What i would like to do is pass a string value from one method to another for example (modifierCmd) and create the relevant Modifier to pass to a separate method.

- (void)methodOne:(NSString *)stringValue {
    Modifier mod = (Modifier)stringValue;
    [self methodTwo:mod];
}

Should this work?

Thanks

Upvotes: 0

Views: 844

Answers (2)

vodkhang
vodkhang

Reputation: 18741

I don't think it can work because the data type is really different. Enum is in fact, integer, when NSString is an object. You can use if else to check for modifier. But I recommend to pass the modifier directly.

Upvotes: 1

mipadi
mipadi

Reputation: 410642

Nope. You can use a function, though:

Modifier makeModifier(NSString *s)
{
    if ([s isEqualToString:@"modifierNone"]) {
        return modifierNone;
    } else if ([s isEqualToString:@"modifierCmd"]) {
        return modifierCmd;
    } /* etc... */
}

- (void)methodOne:(NSString *)stringValue
{
    [self methodTwo:makeModifier(stringValue)];
}

Upvotes: 4

Related Questions