Using named value from enum in Objective C
I have an enum defined as follows:
typedef enum modifiers {
modifierNone=-1,
modifierCmd,
modifierShift,
开发者_如何学Python 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
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)];
}
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.
精彩评论