如何给一个字典的数组排序

我有这样一个数组:

NSArray *arr = @[@{@"index" : @"3", @"key" : @"value"},
                 @{@"index" : @"4", @"key" : @"value"},
                 @{@"index" : @"1", @"key" : @"value"},
                 @{@"index" : @"2", @"key" : @"value"}];

要重新按照字典里的index值排序变成这样:

NSArray *arr = @[@{@"index" : @"1", @"key" : @"value"},
                 @{@"index" : @"2", @"key" : @"value"},
                 @{@"index" : @"3", @"key" : @"value"},
                 @{@"index" : @"4", @"key" : @"value"}];

我现在的做法是遍历数组然后排序的办法。有没有优雅一点的做法。。感觉这样好麻烦

阅读 11k
2 个回答

Compare method

Either you implement a compare-method for your object:

- (NSComparisonResult)compare:(Person *)otherObject {
    return [self.birthDate compare:otherObject.birthDate];
}
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];

NSSortDescriptor (better)
or usually even better: (The default sorting selector of NSSortDescriptor is compare:)

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"birthDate"
                                              ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];

Blocks (shiny!)

There's also the possibility of sorting with a block since 10.6:

NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    NSDate *first = [(Person*)a birthDate];
    NSDate *second = [(Person*)b birthDate];
    return [first compare:second];
}];
NSArray *array = [NSArray array];
    [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
        NSNumber index1 = [obj1 valueForKey:@"index"];
        NSNumber index2 = [obj2 valueForKey:@"index"];
        return [index1 compare:index2];
    }];

就是这样了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题