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

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

最佳答案

我们可以使用2的幂来给出一些唯一的密钥。而且我们可以任意组合这些唯一键,结果仍然是唯一的。
History of the Binary System


  每个数字都有唯一的二进制表示的事实告诉我们
  每个数字都可以用独特的方式表示为
  2的次方幂。由于L. Euler,我希望提供一个独立的证明
  (1707-1783)[Dunham,第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);

关于objective-c - 在局部 View 上变化文字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13563282/

10-14 22:36