Sorting an NSArray of NSDictionary

╄→гoц情女王★ 提交于 2019-12-12 15:24:03

问题


I have to sort an array of dictionaries but I have to order by an object in the dictionaries.


回答1:


Use NSSortDescriptors with -sortedArrayUsingDescriptors:. For the key path, pass in the dictionary key, followed by the object's key(s) by which you want to sort. In the following example, you have an array of dictionaries and those dictionaries have a person under "personDictionaryKey", and the "person" has a "lastName" key.

NSSortDescriptor * descriptor = [[[NSSortDescriptor alloc] initWithKey:@"personInDictionary.lastName" 
        ascending:YES] autorelease]; // 1
NSArray * sortedArray = [unsortedArray sortedArrayUsingDescriptors:
        [NSArray arrayWithObject:descriptor]];

1 - In 10.6 there are class convenience methods for creating sort descriptors but as bbum's answer says, there are now blocks-enabled sorting methods and I'm betting they're a lot faster. Also, I noticed your question is for iOS, so that's probably irrelevant. :-)




回答2:


To rephrase; you want to sort the array by comparing dictionary contents? (I.e. you know you can't sort a dictionary's contents, right?)

As Joshua suggested, use NSSortDescriptor and sortedArrayUsingDescriptors:. This is quite likely the best solution; at least the most straightforward.

There are other ways, too.

Assuming you are targeting iOS 4.0, then you can use sortedArrayUsingComparator: and pass a block that'll do the comparison of the two dictionary's contents.

If you are targeting iOS 3.x (including the iPad), then you would use sortedArrayUsingFunction:context:.

Or, as Joshua suggested, use NSSortDescriptor and sortedArrayUsingDescriptors:

All are quite well documented, with examples.




回答3:


here is an implementation with custom objects instead of dictionaries:

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);


来源:https://stackoverflow.com/questions/3925666/sorting-an-nsarray-of-nsdictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!