2010-08-01 136 views
0

在我的项目中,我浏览了一堆sql记录,并用每个键的字符串填充NSMutableDictionary。这些键很重要,因为我将它们用作TableView中的章节标题。帮助排序NSArray

我遇到的问题是,我想按照特定顺序进行操作。当我调用allKeys时,键的顺序与它们进入NSMutableDictionary的顺序不同。我或多或少地理解了为什么。我的问题是,如何让某些值(非字母)在其余值之前先出现。

例字符串:“蓝”,“布朗”,“绿”,“橙”,“紫”,“红”,“紫”,“黄” ......

我想看看他们这样下令:'红色','绿色','蓝色','棕色','橙色','紫色','红色','紫色'

重要的部分是“红色” '绿色','蓝色'“,所有其他值可以按照这3个值的字母顺序排列。

我能想到的唯一方法是按照字母顺序排列它们,说'sortedArrayUsingSelector:@selector(compare :)',然后试图删除我正在查找的字符串并将它们放回到一个较小的索引值如果它们存在。任何更好的想法?我不知道这是多高效。

回答

0

这是我想出的方法。再次,我不确定它有多高效,但它适用于我的目的。

-(NSArray *)rearrangeSections:(NSArray *)s { 
    NSArray *topSections = [NSArray arrayWithObjects:@"Red", @"Green", @"Blue", nil]; 

    NSArray *reversedTopSections = [[topSections reverseObjectEnumerator] allObjects]; 
    NSArray *alphabetizedArray = [s sortedArrayUsingSelector:@selector(compare:)]; 
    NSMutableArray *sections = [NSMutableArray arrayWithArray:alphabetizedArray]; 

    //Loop through our list of sections and place them at the top of the list. 
    for (NSString *sectionTitle in reversedTopSections) { 
     if ([sections containsObject:sectionTitle]) { 
      [sections removeObject:sectionTitle]; 
      [sections insertObject:sectionTitle atIndex:0]; 
     } 
     //NSLog(@"%@", sections); 
    } 

    NSArray *sortedSections = [NSArray arrayWithArray:sections]; 
    return sortedSections; 
} 
0

你的方法似乎没问题。使用“库存方法”是一个不错的选择。由于您无法对按键顺序进行假设,因此这是一条路。

+0

尝试了我的想法,它没有按照我的希望工作。 NSMutableDictionary并没有将它们保留在我用索引指定的顺序中。 – SonnyBurnette 2010-08-02 01:46:40

+0

NM,我明白了。由于我循环的方式,我得到了一个奇怪的命令。现在很好。 – SonnyBurnette 2010-08-02 02:53:10