请帮我构建一个多维查找表,我想摆脱该死的箭头反模式,而不是使用ifs和switch。
我有两个UIControlStates
UIControlStateNormal UIControlStateHighlighted
双方定义为枚举
EnumSideLeft
EnumSideRight
和两个阴影作为枚举
EnumShadeLight EnumShadeDark
这是一个2 x 2 x 2的立方体。对于每个细胞/三个组合,我有一个独特的图片。
我希望有一个遍历配置字典的类方法,并返回一个UIimage +一个提供配置字典本身的类方法。
但是我无法想出一种有效的方法来使用现代文字方法定义该字典+使用字典的该多维数据集的层次结构。
答案 0 :(得分:4)
您可以将NSDictionary
与特殊键一起使用:
NSDictionary* images = ...;
int x,y,z = ...;
NSString* key = [NSString stringWithFormat:@"%d,%d,%d", x,y,z);
UIImage* image = images[key];
这只是一个想法。您也可以将键构造为具有移位和按位OR运算的整数,例如:
int key = (z<<4) | (y<<2) | x;
然后为密钥创建一个NSNumber。这比生成NSString
更快。
答案 1 :(得分:1)
我可能会采用CouchDeveloper建议的方法,但如果您想要在您的问题中描述的内容,请尝试以下内容:
static NSDictionary *configDict;
typedef NS_ENUM(NSUInteger, BDSide) {
BDSideLeft,
BDSideRight
};
typedef NS_ENUM(NSUInteger, BDShade) {
BDShadeLight,
BDShadeDark
};
+ (UIImage *)configurationForState:(UIControlState)state Side:(BDSide)side Shade:(BDShade)shade
{
UIImage *result = nil;
NSDictionary *stateDictionary = [configDict objectForKey:@(state)];
NSDictionary *sideDictionary = [stateDictionary objectForKey:@(side)];
result = [sideDictionary objectForKey:@(shade)];
return result;
}
+(void)initialize
{
configDict = @{@(UIControlStateNormal):
@{@(BDSideLeft):
@{@(BDShadeLight): [UIImage imageNamed:@"normal-left-light.png"],
@(BDShadeDark): [UIImage imageNamed:@"normal-left-dark.png"]},
@(BDSideRight):
@{@(BDShadeLight): [UIImage imageNamed:@"normal-right-light.png"],
@(BDShadeDark): [UIImage imageNamed:@"normal-right-dark.png"]}},
@(UIControlStateHighlighted):
@{@(BDSideLeft):
@{@(BDShadeLight): [UIImage imageNamed:@"highlight-left-light.png"],
@(BDShadeDark): [UIImage imageNamed:@"highlight-left-dark.png"]},
@(BDSideRight):
@{@(BDShadeLight): [UIImage imageNamed:@"highlight-right-light.png"],
@(BDShadeDark): [UIImage imageNamed:@"highlight-right-dark.png"]}}};
}