2014-03-02 67 views
-2

我已經按照名字組織的第一個字母(見下面的結果)創建排序數組的NSDictionary。當我使用命令allKeys爲同一個詞典時,順序是不一樣的。我需要相同的順序,因爲這個NSDictionary在UITableview中使用,應該是按字母順序的。NSDictionary命令不匹配allKeys命令

- (NSDictionary*) dictionaryNames { 

NSDictionary *dictionary; 
NSMutableArray *objects = [[NSMutableArray alloc] init]; 

NSArray *letters = self.exhibitorFirstLetter; 
NSArray *names = self.exhibitorName; 

for (NSInteger i = 0; i < [self.exhibitorFirstLetter count]; i++) 
{ 
    [objects addObject:[[NSMutableArray alloc] init]]; 
} 

dictionary = [[NSDictionary alloc] initWithObjects: objects forKeys:letters]; 

for (NSString *name in names) { 
    NSString *firstLetter = [name substringToIndex:1]; 

    for (NSString *letter in letters) { //z, b 
     if ([firstLetter isEqualToString:letter]) { 
      NSMutableArray *currentObjects = [dictionary objectForKey:letter]; 
      [currentObjects addObject:name]; 
     } 
    } 

} 

    NSLog(@"%@", dictionary); 
NSLog(@"%@", [dictionary allKeys]); 
return dictionary; 

}

B =  (
    "Baker's Drilling", 
    "Brown Drilling" 
); 
C =  (
    "Casper Drilling" 
); 
J =  (
    "J's, LLC" 
); 
N =  (
    "Nelson Cleaning", 
    "North's Drilling" 
); 
T =  (
    "Tim's Trucks" 
); 
Z =  (
    "Zach's Main", 
    "Zeb's Service", 
    "Zen's" 
); 

}

J, 
T, 
B, 
N, 
Z, 
C 

+4

這是因爲NSDictionary的關鍵是沒有順序的。如果你想讓他們訂購,把它們放在一個數組中。 – danielbeard

+0

可能的重複[NSDictionary鍵順序保證與初始化相同,如果它永遠不會改變?](http://stackoverflow.com/questions/2496430/is-nsdictionary-key-order-guaranteed-the-same-as-initialized -if-it-never-changes),[NSDictionary allKeys - 是否總是返回相同的順序?](http://stackoverflow.com/q/9575387),[NSDictionary allKeys order](http:// stackoverflow。 com/q/17745212) –

+0

感謝您的建議,現在已解決! – Bachzen

回答

4

的NSDictionary不是一個有序集合。沒有辦法控制它如何訂購東西,它可能完全取決於操作系統版本,設備類型和字典內容。

1

我只是把在NSDictionary的數組排序:

- (NSArray*)sortAllKeys:(NSArray*)passedArray{ 
    NSArray* performSortOnKeys = [passedArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 
    return performSortOnKeys; 
} 
+0

雖然@bachazen很好的工作 –