5

How to sort NSMutable array in ascending order. Can any one help me out this.

4 Answers 4

4

You haven't said what's in your array, but if it's something that responds to -compare: then you can use

[myArray sortUsingSelector:@selector(compare):];
Sign up to request clarification or add additional context in comments.

Comments

3

Here is a way to sort an array of object

    NSSortDescriptor * descFirstname = [[NSSortDescriptor alloc] initWithKey:@"firstname" ascending:YES];
NSSortDescriptor * descLastname = [[NSSortDescriptor alloc] initWithKey:@"lastname" ascending:YES];
[myArrayOfPerson sortUsingDescriptors:[NSArray arrayWithObjects:descLastname,descFirstname, nil]];
    [descFirstname release];
    [descLastname release];

2 Comments

Don't forgot to (auto)release the objects.
@DarkDust Of course! I forgot it but correct the sample code ;) Thanks
1

Yes, you can use a NSSortDescriptor, have a look at Sort Descriptor Programming Topics.

Comments

1
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:nil
ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [sortValuesArray sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"sortedArray%@",sortedArray);

sortValuesArray is the array that you want to sort.

2 Comments

You didn't even specify a key.
I have done this code with sorting array which contain numbers so there were no key and mostly the arrays dont have key that why.But no matters It's good that you got the solution ....happy coding...:)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.