我在objective-c应用程序中有一些常量,我需要使用字符串从外部源输入。当然,原因是常量更好,但不能在外部传递。
我已经使这个Objective-c代码转换,并且它100%工作,但a)它很难看,而且b)相当模糊。我想我可以转换为NSNumber并制作一个数组,但这似乎是很多代码/处理(虽然可能是正确的解决方案)
任何人都可以提供更好的解决方案吗?
NSArray *types = @[@"text_input",@"textbox",@"select",@"yesno",@"date",@"signature",@"label",@"SectionHeading"];
int indexes[10];
indexes[0] = FieldTypeTextInput;
indexes[1] = FieldTypeTextBox;
indexes[2] = FieldTypeSelect;
indexes[3] = FieldTypeYesNo;
indexes[4] = FieldTypeDate;
indexes[5] = FieldTypeSignature;
indexes[6] = FieldTypeLabel;
indexes[7] = FieldTypeSectionHeading;
for (int i=0;i<[types count];i++)
{
NSString *string_i = [types objectAtIndex:i];
if ([type_string isEqualToString:string_i])
答案 0 :(得分:1)
我建议使用NSDictionary
。
enum YourNiceTypes : NSInteger {FieldNotFound, FieldTypeTextInput, FieldTypeTextBox, ...};
NSDictionary *types = @{"text_input" : @(FieldTypeTextInput), ... };
enum YourNiceType type = [types[textInput] integerValue];
您使用该技巧定义了错误的输入零,这将自动正确处理,因为在integerValue
对象上调用nil
将返回0
。