-2

I've below NSMutableArray

I want to sort array element according to DOBDate by Ascending order

Sort by Name key in alphabetic order.

myarraytosort":[  
    {“DOBDate":"Jul 18, 1987”,”Name”:”Aman Singh”},
    {“DOBDate”:”Dec 18, 2000”,”Name”:”Dman Kumar”},
    {“DOBDate”:”June 18, 1990”,”Name”:”Cman Singh”},
    nil
]

Code I try but not working

for DOBDate

 NSSortDescriptor *dateDescriptor = [NSSortDescriptor
                                            sortDescriptorWithKey:@"DOBDate"
                                            ascending:NO];
        NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
        NSArray *sortedEventArray = [myarraytosort
                                     sortedArrayUsingDescriptors:sortDescriptors];
        NSLog(@"sortedEventArray == %@", sortedEventArray);

For alphabet

NSSortDescriptor *dateDescriptor = [NSSortDescriptor
                                            sortDescriptorWithKey:@"Name"
                                            ascending:YES];
        NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
        NSArray *sortedEventArray = [myarraytosort
                                     sortedArrayUsingDescriptors:sortDescriptors];
        NSLog(@"sortedEventArray == %@", sortedEventArray);
Nirav D
  • 71,513
  • 12
  • 161
  • 183
9to5ios
  • 5,319
  • 2
  • 37
  • 65
  • Check this http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it?rq=1 – Amit Kalghatgi Jul 26 '16 at 11:55
  • 4
    It would be better to use `NSDate` instead of `NSString` object to represent the date. Else, you have to use `sortUsingComparator:` and a custom comparator (with a `NSDateFormatter`). – Larme Jul 26 '16 at 11:55

1 Answers1

1

Your DOBDate key contains date in string formate so you need to sort your date using Comparator like this way

NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"MMM dd, yyyy"];
NSArray *sortedArray = [yourArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
    NSDate *d1 = [df dateFromString:(NSString*) [obj1 valueForKey:@"DOBDate"]];
    NSDate *d2 = [df dateFromString:(NSString*) [obj2 valueForKey:@"DOBDate"]];
    return [d1 compare: d2];
}];
Nirav D
  • 71,513
  • 12
  • 161
  • 183
  • Welcome mate Happy Coding :) – Nirav D Jul 26 '16 at 12:54
  • I'd recommend to put `df` outside the `NSComparisonResult()` because the alloc/init of a `NSDateFormatter` is time (and CPU) consuming and it is always the same one. – Larme Jul 26 '16 at 13:05