Home Ask Login Register

Developers Planet

Your answer is one click away!

amar February 2016

How to Sort NSMutable Array

I am having NSMutableArray containing objects like [1,10,100,101,32A,32B,75,76,77,GAOTHAN], I want to sort this array in ascending order. I am using below code but it is not working, As I don't have any key in my array. If anybody having solution please let me know.

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"self" 
NSArray *descriptors = [NSArray arrayWithObject:descriptor];
NSArray *reverseOrder = [dateArray sortedArrayUsingDescriptors:descriptors];


Crazy Developer February 2016

you need to add compare method

- (NSComparisonResult)compare:(NSString *)otherObject {
    return [self compare:otherObject];

Call this method using the below code which return you sorted array.

NSMutableArray * arrayToFilter = [NSMutableArray arrayWithObjects:@"1",@"10",@"100",@"101",@"32A",@"32B",@"75",@"76",@"77",@"GAOTHAN",nil];

NSArray *sortedArray = [arrayToFilter sortedArrayUsingSelector:@selector(compare:)];

you can write you own logic to compare two object of your array.

amar February 2016

I got it

      NSMutableArray *unsortedArray = [NSMutableArray arrayWithObjects:@"1",@"10",@"100",@"32A",@"32B",@"GAOTHAN", nil];
    NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(id firstObject, id secondObject)
        return [((NSString *)firstObject) compare:((NSString *)secondObject) options:NSNumericSearch]; }];
    NSLog(@"Array is ::%@",sortedArray);

Post Status

Asked in February 2016
Viewed 1,966 times
Voted 4
Answered 2 times


Leave an answer

Quote of the day: live life