iphonemaclover iphonemaclover - 4 months ago 14
iOS Question

Sort NSMutableArray with key value

I've below NSMutableArray

I want to sort array element according to DOBDate 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);

Answer

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];
}];
Comments