1

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

例子

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

5 回答 5

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";
 };
);
于 2013-11-01T08:05:26.613 回答
0

使用 NSSortDescriptor:

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

myArray 是要排序的数组。

于 2013-11-01T08:01:26.967 回答
0

正如您在评论中回答的那样,所有数组元素中的第一个字典键都是“Person1”。那么“Person1.firstName”是给出每个数组元素名字的关键路径。此键路径可用于排序描述符:

NSArray *array = ... // your array
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"Person1.firstName" ascending:YES];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:@[sort]];
于 2013-11-01T08:36:06.293 回答
0

首先,您应该为您的对象实现一个比较方法。

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

NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];
于 2013-11-01T07:56:47.893 回答
0

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

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

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

}];
于 2013-11-01T07:58:33.013 回答