我需要对一个字典数组进行排序,但是排序的依据是字典中的一个对象。
我需要对一个字典数组进行排序,但是排序的依据是字典中的一个对象。
NSSortDescriptor * descriptor = [[[NSSortDescriptor alloc] initWithKey:@"personInDictionary.lastName"
ascending:YES] autorelease]; // 1
NSArray * sortedArray = [unsortedArray sortedArrayUsingDescriptors:
[NSArray arrayWithObject:descriptor]];
1 -在10.6中,有用于创建排序描述符的类便捷方法,但正如bbum的答案所说,现在有了启用块的排序方法,我打赌它们会更快。此外,我注意到你的问题是关于iOS的,所以那可能是无关紧要的。 :-)
这里有一个使用自定义对象而不是字典的实现:
ArtistVO *artist1 = [ArtistVO alloc];
artist1.name = @"Trentemoeller";
artist1.imgPath = @"imgPath";
ArtistVO *artist2 = [ArtistVO alloc];
artist2.name = @"ATrentemoeller";
artist2.imgPath = @"imgPath2";
ArtistVO *artist3 = [ArtistVO alloc];
artist3.name = @"APhextwin";
artist3.imgPath = @"imgPath2";
//NSLog(@"%@", artist1.name);
NSMutableArray *arr = [NSMutableArray array];
[arr addObject:artist1];
[arr addObject:artist2];
[arr addObject:artist3];
NSSortDescriptor *lastDescriptor =
[[[NSSortDescriptor alloc]
initWithKey:@"name"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)] autorelease];
NSArray * descriptors =
[NSArray arrayWithObjects:lastDescriptor, nil];
NSArray * sortedArray =
[arr sortedArrayUsingDescriptors:descriptors];
NSLog(@"\nSorted ...");
NSEnumerator *enumerator;
enumerator = [sortedArray objectEnumerator];
ArtistVO *tmpARt;
while ((tmpARt = [enumerator nextObject])) NSLog(@"%@", tmpARt.name);