2010-08-01 82 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