How can I sort an NSArray containing NSDictionaries?

非 Y 不嫁゛ 提交于 2019-11-26 06:48:04

问题


I have an NSArray which contains NSDictionary objects. Each of these NSDictionary objects contains an ORDER key.

How can I sort this NSArray based on this key within each of these NSDictionaries?


回答1:


Here is an example. Imagines you have an array of dictionnaries. Ecah dictionnary have 2 keys "name" & "dateOfBirth". You can sort your array by "name" like this :

//
// Sort array by name
//
NSSortDescriptor *Sorter = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
[myArray sortUsingDescriptors:[NSArray arrayWithObject:Sorter]];
[Sorter release];

Note that myArray is a NSMutableArray.




回答2:


Read the Sorting with Sort Descriptors section of Apple's Collections Programming Topics.

The example in this section covers sorting an array of dictionary objects by their keys.




回答3:


To Sort array of dictionaries you have to use NSSortDescriptor by this you can sort array of dictionaries based on key

here in code, pass the NSMutableArray with dict Object by mean which you want to sort it

-(NSMutableArray*)sortingArrayOfDict:(NSMutableArray *)arrayTosort sortByObject:(NSString*)sortKey{
NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:YES];
[arrayTosort sortUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]];
return arrayTosort;
 }

or even you can sort it in ascending or descending order by setting it YES/NO



来源:https://stackoverflow.com/questions/3361207/how-can-i-sort-an-nsarray-containing-nsdictionaries

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