Malloc
Malloc

Reputation: 16256

sorting a nested NSMutableArray

the NSMutableArray I want to sort looks like this:

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

It's an NSMutableArray which contain a collection of NSMutableArrays. I want to sort it by price first then by title.

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

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

However, that didn't seems to work, how to sort a nested NSMutableArray?

Upvotes: 0

Views: 392

Answers (3)

Anupdas
Anupdas

Reputation: 10201

Try

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

Upvotes: 5

user4003752
user4003752

Reputation:

Try this

Apple doc

This well help you

Upvotes: 0

user529758
user529758

Reputation:

I suppose the error is that price is a string. As such, it isn't compared numerically, but lexicographically. Try sorting the array using a comparator block and parsing the price inside that block instead:

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

Upvotes: 1

Related Questions