Sorting Array in iphone SDK

Sorting as its name defines arranging certain item in an order way.In many of our iPhone apps, we requires sorting with which we can sort are array in an order way. e.g. we need to arrange list of our friends in alphabetical order or arrange number sequence in increasing or decreasing order. For the solution to sort an array, we can use NSSortDescriptor provided in Xcode.

According to the documentation it says, NSSortDescriptor describes a basis for ordering objects by specifying the property to use to compare the objects, the method to use to compare the properties, and whether the comparison should be ascending or descending. Instances of NSSortDescriptor are immutable.

So let’s jump into it and see how we can use this beautiful technique to sort our data.Suppose we have an array that contains list of our friends as a dictionary called friendListArray.
In .h file create an instance of  friendListArray

    NSMutableArray *friendListArray;

Now, open your .m file and in viewDidLoad alloc and initialize it and add our friends name.

friendListArray = [[NSMutableArray alloc]initWithCapacity:0];
 [friendListArray addObject:@{@”Name”: @”Ramesh”}];
 [friendListArray addObject:@{@”Name”: @”Sumit”}];
 [friendListArray addObject:@{@”Name”: @”Aman”}];
 [friendListArray addObject:@{@”Name”: @”Nitish”}];
 [friendListArray addObject:@{@”Name”: @”Gagan”}];
 [friendListArray addObject:@{@”Name”: @”Aseem”}];
 [friendListArray addObject:@{@”Name”: @”Parshant”}];
 [friendListArray addObject:@{@”Name”: @”Abhishek”}];

As you are seeing that our array contains name in an un-ordered way i.e they are not arranged in alphabetical order.To arrange them we can use NSSortDescriptor.
First create an instance of NSSortDescriptor using method initWithKey(need to pass key, according to which it return sorted array, if we have no dictionary or ke in our array then pass nil). Here we pass Name as we have to arrange our data according to Name i.e. alphabetical order

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc]initWithKey:@”Name” ascending:YES];

Since we create our NSSortDescriptor, we will l sort data using  sortedArrayUsingDescriptors method of array.This method will return us an array. Here i am using arrayWithArray method of NSNSMutableArray because i need an mutable instancepf array and sortedArrayUsingDescriptors method return immutable array.

[NSMutableArray arrayWithArray:[friendListArray sortedArrayUsingDescriptors:@[descriptor]]];

Now print this in NSLog, it will return sorted array with names are arranged in alphabetical order

 NSLog(@”Sorted Array == %@”,[NSMutableArray arrayWithArray:[friendListArray sortedArrayUsingDescriptors:@[descriptor]]]);