Sort array of NSDictionaries by a value inside one of the keys

This question already has an answer here:

  • How do I sort an NSMutableArray with custom objects in it? 25 answers
  • Sorting NSArray of dictionaries by value of a key in the dictionaries 10 answers

  • 使用以下内容;

    NSArray *sortedArray;
    sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *first, NSDictionary *second) {
        // Calculate distances for each dictionary from the device
        // ...
        return [firstDistance compare:secondDistance];
    }];
    

    Unfortunately you can't sort NSDictionary objects. You should create NSMutableArray and sort it instead.

    See this - Collections Programming Topics - Sorting Arrays

    Update: To sort array of dictionaries you can use for example this method of NSArray:

    sortedArray = [someArray sortedArrayUsingFunction:compareElements context:NULL];
    

    The compareElements function example:

    NSInteger compareElements (id num1, id num2, void *context)
    {
        int v1 = [[num1 objectForKey:@"distance"] integerValue];
        int v2 = [[num2 objectForKey:@"distance"] integerValue];
        if (v1 < v2)
            return NSOrderedAscending;
        else if (v1 > v2)
            return NSOrderedDescending;
        else
            return NSOrderedSame;
    }
    
    链接地址: http://www.djcxy.com/p/70810.html

    上一篇: 按对象值排序NSMutableArray

    下一篇: 使用其中一个键内的值对NSDictionaries数组进行排序