0

I am an Iphone developer and I am new to this technology. I want to sort an NSMutableArray. At every index of this array, there is an NSMutableDictionary. Every dictionary has two fields : Name and Date. I want to sort the array according to this Date field . My array looks like following :

(
   {
       name :  raj
       date  : 20/09/1998
   }
   {
       name : teena
       date : 21/06/1987
   }
)

I searched on net a lot but couldn't find any appropriate answer. Please help me guys. Any response will highly be appreciated.

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
  • I think what you want is well Described Here : [How to sort an NSMutableArray with custom objects in it?](http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it) You can modify the answer according to your requirement. – Bhavin Jan 16 '13 at 07:12

1 Answers1

1
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"date"
                                              ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
self.sortedArray = [self.originalArray sortedArrayUsingDescriptors:sortDescriptors];

This should work if your date key actually contains a date object and if it contains a date in the form of string.. than you will have to try this..

[resultArray sortUsingComparator:^NSComparisonResult(id a, id b) {

    static NSDateFormatter *dateFormatter = nil;

    if (!dateFormatter) {
        dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"mm/dd/yyyy hh:mm:ss"; 
    }

    NSString *date1String = [a valueForKey:@"StartDate"];
    NSString *date2String = [b valueForKey:@"StartDate"];

    NSDate *date1 = [dateFormatter dateFromString:date1String];
    NSDate *date2 = [dateFormatter dateFromString:date2String];

    return [date1 compare:date2];
    }];
KingofBliss
  • 15,055
  • 6
  • 50
  • 72
Ankit Srivastava
  • 12,347
  • 11
  • 63
  • 115