如何对包含NSDictionaries的Array进行排序

时间:2013-11-01 07:46:56

标签: ios objective-c arrays ios6 nssortdescriptor

假设我想按“firstName”键对数组进行排序。

实施例

Array = (
   {
     People1 = {
         firstName = @"Jack Adam";
         email = @"adam@gmail.com";
     };
     Address = {
         cityCode = @"TH";
     };
   },
     People2 = {
         firstName = @"Jack DAm";
         email = @"dam@gmail.com";
     };
      Address = {
         city = @"TH";
     };
);

5 个答案:

答案 0 :(得分:2)

用户排序比较器

NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(NSDictionary *a, NSDictionary *b) {

  return [a[@"People"][@"firstname"] compare:b[@"People"][@"firstname"]];

}];

但你的关键是不一致...... 我认为数据应该是

Array = (
{
 People = {
     firstName = @"Jack Adam";
     email = @"adam@gmail.com";
 };
 Address = {
     cityCode = @"TH";
 };
},
 People = {
     firstName = @"Jack DAm";
     email = @"dam@gmail.com";
 };
  Address = {
     city = @"TH";
 };
);

答案 1 :(得分:0)

首先,您应该为对象实现compare-method。

- (NSComparisonResult)compare:(Person *)otherObject {
    return [self.birthDate compare:otherObject.birthDate];
}

NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];

答案 2 :(得分:0)

使用块和现代Objective-C语法:

NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(NSDictionary *first, NSDictionary *second) {

      return [first[@"Person"] compare:second[@"Person"]];

}];

答案 3 :(得分:0)

使用NSSortDescriptor:

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"firstName"  ascending:YES];
    myArray=[stories sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
    temp = [stories copy]; //temp is NSMutableArray

myArray是您要排序的数组。

答案 4 :(得分:0)

当您在评论中回复时,第一个字典键是" Person1"在所有数组元素中。 然后" Person1.firstName"是 密钥路径 ,它给出了每个数组的名字 元件。此密钥路径可用于排序描述符:

NSArray *array = ... // your array
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"Person1.firstName" ascending:YES];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:@[sort]];