我有一个带有项目的表视图。如果我点击某个项目,则会显示其详细视图。 现在每个项目都有两个表示有意义状态的枚举状态。第一个枚举有6个不同的值,第二个枚举可以有5个不同的值。这给了我30个组合。 对于每个组合,我需要一个独特的文本。
在cellForRowAtIndexPath中提供正确的文本时:...我应该使用什么技术从该网格中选择正确的文字"? 开关结构非常大。有更简洁的解决方案吗?
答案 0 :(得分:1)
我们可以使用2的幂来给出一些独特的密钥。我们可以随意复合这些唯一键,结果仍然是唯一的。 History of the Binary System
每个数字都有唯一的二进制表示这一事实告诉我们 每个数字都可以用一种独特的方式表示为 由于L.欧拉,我希望提供一份独立的证据 (1707-1783)[Dunham,p 166]后者的结果。
代码:
typedef enum {
FirstTypeOne = 1 << 0,
FirstTypeTwo = 1 << 1,
FirstTypeThree = 1 << 2,
FirstTypeFour = 1 << 3,
FirstTypeFive = 1 << 4,
FirstTypeSix = 1 << 5
} FirstType;
typedef enum {
SecondTypeSeven = 1 << 6,
SecondTypeEight = 1 << 7,
SecondTypeNine = 1 << 8,
SecondTypeTen = 1 << 9,
SecondTypeEleven = 1 << 10
} SecondType ;
const int FirstTypeCount = 6;
const int SecondTypeCount = 5;
// First create two array, each containing one of the corresponding enum value.
NSMutableArray *firstTypeArray = [NSMutableArray arrayWithCapacity:FirstTypeCount];
NSMutableArray *secondTypeArray = [NSMutableArray arrayWithCapacity:SecondTypeCount];
for (int i=0; i<FirstTypeCount; ++i) {
[firstTypeArray addObject:[NSNumber numberWithInt:1<<i]];
}
for (int i=0; i<SecondTypeCount; ++i) {
[secondTypeArray addObject:[NSNumber numberWithInt:1<<(i+FirstTypeCount)]];
}
// Then compute an array which contains the unique keys.
// Here if we use
NSMutableArray *keysArray = [NSMutableArray arrayWithCapacity:FirstTypeCount * SecondTypeCount];
for (NSNumber *firstTypeKey in firstTypeArray) {
for (NSNumber *secondTypeKey in secondTypeArray) {
int uniqueKey = [firstTypeKey intValue] + [secondTypeKey intValue];
[keysArray addObject:[NSNumber numberWithInt:uniqueKey]];
}
}
// Keep the keys asending.
[keysArray sortUsingComparator:^(NSNumber *a, NSNumber *b){
return [a compare:b];
}];
// Here you need to put your keys.
NSMutableArray *uniqueTextArray = [NSMutableArray arrayWithCapacity:keysArray.count];
for (int i=0; i<keysArray.count; ++i) {
[uniqueTextArray addObject:[NSString stringWithFormat:@"%i text", i]];
}
// Dictionary with unique keys and unique text.
NSDictionary *textDic = [NSDictionary dictionaryWithObjects:uniqueTextArray forKeys:keysArray];
// Here you can use (FirstType + SecondType) as key.
// Bellow is two test demo.
NSNumber *key = [NSNumber numberWithInt:FirstTypeOne + SecondTypeSeven];
NSLog(@"text %@ for uniquekey %@", [textDic objectForKey:key], key);
key = [NSNumber numberWithInt:FirstTypeThree + SecondTypeNine];
NSLog(@"text %@ for uniquekey %@", [textDic objectForKey:key], key);