0

Based on an NSMutableArray of NSMutableDictionarys, I try to sort it based on a key by ascending order. the key is called Product Sale Price and it's returned from server as a string like $350. So I substring the first character to compare int values:

//Sorting function
NSInteger priceComparator(NSMutableDictionary *obj1, NSMutableDictionary *obj2, void *context){
    int v1 = [[[obj1 valueForKey:@"Product Sale Price"]substringFromIndex:1] intValue];
    int v2 = [[[obj2 valueForKey:@"Product Sale Price"]substringFromIndex:1] intValue];
    NSLog(@"v1, v2: %i | %i",v1,v2);
    if (v1 > v2){

        NSLog(@"v2 is smaller: <%i>",v2);
        return v2;
    }
    else if (v1 < v2){

        NSLog(@"v1 is smaller: <%i>",v1);
        return v1;   
    }
    else
        return NSOrderedSame;
}


//Somewhere in the code
arrayProduct = (NSMutableArray*)[arrayProduct sortedArrayUsingFunction:priceComparator context:nil];
NSLog(@"%@",arrayProduct);//The array is not sorted as expected, still random order

So basically, the order is not affected somehow although I debugged that step b step and all comparisons are correct. Am I missing something?

EDIT:

Here is some items of arrayProduct:

(
    {
        "Product ID" = 15119;
        "Product Sale Price" = "$395";
    },

    {
        "Product ID" = 16897;
        "Product Sale Price" = "$75";
    }
)

2 Answers 2

3

You need to return NSOrderedAscending and NSOrderedDescending instead of v1 and v2. If the sort ends up in reverse order - swap which of the two you return.

Sign up to request clarification or add additional context in comments.

Comments

0

you can use sort descriptor for sorting array like below code here key is key of parameter on which you want to sorting array. e.g you want to sort by name then key is "name"

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.