0

我有一个包含项目的表格视图。如果我单击一个项目,则会显示它的详细视图。现在每个项目都有两个枚举状态,代表一个有意义的状态。第一个枚举有 6 个不同的值,第二个枚举可以有 5 个不同的值。这给了我 30 种组合。对于每种组合,我都需要一个独特的文本。

在 cellForRowAtIndexPath 中提供正确的文本时:...我应该使用什么技术从该“网格”中选择正确的文本?开关结构相当大。有没有更简洁的解决方案?

4

1 回答 1

1

我们可以使用 2 的幂来给出一些唯一的键。而且我们可以任意组合这些唯一键,结果仍然是唯一的。 二进制系统的历史

每个数字都有唯一的二进制表示这一事实告诉我们,每个数字都可以用唯一的方式表示为 2 的幂之和。由于 L. Euler (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);
于 2012-11-26T12:13:53.333 回答