Sorting array of dictionaries based on NSNumber

This question already has an answer here:

  • How do I sort an NSMutableArray with custom objects in it? 25 answers

  • You can sorting dictionary using NSSortDescriptor. Please try this :

      // 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);
    

    You can do this easily with -[NSArray sortedArrayUsingComparator:] and a comparison block.

    The comparison block needs to return NSComparisonResult . Fortunately, your values associated with key "id" are NSNumber s, so simply return the result of -[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"]];
    }];
    

    NSArray is immutable so to sort your array you can replace it with a sorted version like this:

    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];
    }
    

    Another method would be to instead use an NSMutableArray and then sort that in a similar way.

    链接地址: http://www.djcxy.com/p/70832.html

    上一篇: iOS:对核心数据对象的NSArray进行排序

    下一篇: 根据NSNumber对字典数组进行排序