Ios 基于NSNumber的字典排序数组
我有一个字典数组,其中键@“id”的编号为NSNumber。我想根据@“id”值对该数组进行排序。如何执行此操作?NSArray是不可变的,因此要对数组进行排序,您可以将其替换为排序后的版本,如下所示:Ios 基于NSNumber的字典排序数组,ios,arrays,sorting,nsarray,nsdictionary,Ios,Arrays,Sorting,Nsarray,Nsdictionary,我有一个字典数组,其中键@“id”的编号为NSNumber。我想根据@“id”值对该数组进行排序。如何执行此操作?NSArray是不可变的,因此要对数组进行排序,您可以将其替换为排序后的版本,如下所示: NSArray * myArray = SortArray(myArray); // SortArray works like this. // Helper function. NSInteger MyComparisonFunction(id a, id b, void* context
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,然后以类似的方式对其进行排序。您可以使用
-[NSArray SortedArray UsingComparator::
和比较块轻松完成此操作
比较块需要返回NSComparisonResult
。幸运的是,与键“id”关联的值是NSNumber
s,因此只需返回-[NSNumber compare:][/code>的结果即可
// 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"]];
}];
您可以使用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);