2014-03-02 69 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很好的工作 –