0

NSMutableArray想排序看起来像这样:

 (
        {
            "title" = "Bags";
            "price" = "$200";
        },
        {
            "title" = "Watches";
            "price" = "$40";
        },
        {
            "title" = "Earrings";
            "price" = "$1000";
        }
 )

它是一个NSMutableArray包含NSMutableArrays 的集合。我想先排序,price然后再排序title

NSSortDescriptor *sortByPrices = [[NSSortDescriptor alloc] initWithKey:@"price" ascending:YES];
NSSortDescriptor *sortByTitle = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];

[arrayProduct sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sortByPrices,sortByTitle,nil]];

但是,这似乎不起作用,如何对嵌套进行排序NSMutableArray

4

3 回答 3

5

尝试

    NSMutableArray  *arrayProducts = [@[@{@"price":@"$200",@"title":@"Bags"},@{@"price":@"$40",@"title":@"Watches"},@{@"price":@"$1000",@"title":@"Earrings"}] mutableCopy];

    NSSortDescriptor *priceDescriptor = [NSSortDescriptor sortDescriptorWithKey:@""
                                                                 ascending:YES
                                                                comparator:^NSComparisonResult(NSDictionary  *dict1, NSDictionary *dict2) {
                                                                    return [dict1[@"price"] compare:dict2[@"price"] options:NSNumericSearch];
    }];

    NSSortDescriptor *titleDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES];



    [arrayProducts sortUsingDescriptors:@[priceDescriptor,titleDescriptor]];

    NSLog(@"SortedArray : %@",arrayProducts);
于 2013-07-31T08:46:03.830 回答
1

我想错误是那price是一个字符串。因此,它不是按数字比较,而是按字典顺序比较。尝试使用比较器块对数组进行排序,并改为解析该块内的价格:

[array sortUsingComparator:^(id _a, id _b) {
    NSDictionary *a = _a, *b = _b;

    // primary key is the price
    int priceA = [[a[@"price"] substringFromIndex:1] intValue];
    int priceB = [[b[@"price"] substringFromIndex:1] intValue];

    if (priceA < priceB)
        return NSOrderedAscending;
    else if (priceA > priceB)
        return NSOrderedDescending;
    else // if the prices are the same, sort by name
        return [a[@"title"] compare:b[@"title"]];
}];
于 2013-07-31T08:33:08.617 回答
0

尝试这个

苹果文档

这个好帮到你

于 2013-07-31T08:39:10.713 回答