基于NSNumber对字典数组进行排序

时间:2014-09-02 02:17:54

标签: ios arrays sorting nsarray nsdictionary

我有一系列字典,其中包含关键字@" id"的NSNumber。我想根据@" id"对这个数组进行排序。值。我该怎么办?

3 个答案:

答案 0 :(得分:1)

您可以使用-[NSArray sortedArrayUsingComparator:]和比较块轻松完成此操作。

比较块需要返回NSComparisonResult。幸运的是,您的值与key" id"相关联。是NSNumber s,因此只需返回-[NSNumber compare:]的结果。

// Example array containing three dictionaries with "id" keys
NSArray *unsortedArray = @[@{ @"id": @3 },  @{ @"id": @1 }, @{ @"id": @2 }];

NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    return [obj1[@"id"] compare:obj2[@"id"]];
}];

答案 1 :(得分:1)

您可以使用NSSortDescriptor对字典进行排序。请试试这个:

  // Example array containing three dictionaries with "id" and "name" keys
  NSArray *unsortedArray = @[@{ @"id":@3, @"name":@"abc"}, @{ @"id":@1, @"name":@"123" }, @{ @"id": @2, @"name":@"xyz" }];
  NSLog(@"Unsorted Array === %@", unsortedArray);

  NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                    initWithKey: @"id" ascending: YES];
  NSArray *sortedArray = [unsortedArray sortedArrayUsingDescriptors: [NSArray arrayWithObject:sortDescriptor]];
  NSLog(@"Sorted Array ==== %@", sortedArray);

答案 2 :(得分:0)

NSArray是不可变的,所以要对数组进行排序,你可以用这样的排序版本替换它:

NSArray * myArray = SortArray(myArray);

// SortArray works like this.

// Helper function.
NSInteger MyComparisonFunction(id a, id b, void* context) {
  NSNumber *aNum = (NSNumber*)a[@"id"];
  NSNumber *bNum = (NSNumber*)b[@"id"];
  return [aNum compare:bNum];
}

NSArray* SortArray (NSArray* unsorted) {
  return [unsorted sortedArrayUsingFunction:MyComparisonFunction context:nil];
}

另一种方法是使用NSMutableArray,然后以类似的方式对其进行排序。