Sort NSArray from NSDictionaries by row date in key?

I am trying to find an easy way to sort NSMutableArray that contains NSDictionaries. Each NSDictionary has a key named "Date" that contains the NSString of the date (for example: 10/15/2014).

What I want to do is sort the array based on these rows in ascending order.

I tried this with no luck:

NSComparisonResult dateSort(NSString *s1, NSString *s2, void *context) { NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"MM/dd/yy"]; NSDate *d1 = [formatter dateFromString:s1]; NSDate *d2 = [formatter dateFromString:s2]; return [d1 compare:d2]; // ascending order return [d2 compare:d1]; // descending order } 

I also tried this with no luck:

 NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest" ascending:YES]; stories=[stories sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]]; recent = [stories copy]; 

Each method crashes, and I think this is because it is NSString instead of NSDate, but I just don't understand how to do it.

Can someone show me the correct way to do this?

This is how I call the first block of code:

 theDictionaries = [[theDictionaries sortedArrayUsingFunction:dateSort context:nil] mutableCopy]; 
+6
source share
2 answers

You need to get lines in dictionaries. It looks like you are trying to compare the dictionaries themselves. If you have an array called data, you would do something like this,

 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"MM/dd/yyyy"]; self.data = [self.data sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) { NSDate *d1 = [formatter dateFromString:obj1[@"date"]]; NSDate *d2 = [formatter dateFromString:obj2[@"date"]]; return [d1 compare:d2]; // ascending order return [d2 compare:d1]; // descending order }]; NSLog(@"%@",self.data); 
+11
source

if you want to sort using Model Class, you should use it.

 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"yyyy-MM-dd hh:mm a"]; finalCompleteArray = [finalCompleteArray sortedArrayUsingComparator:^NSComparisonResult(MessageChat *obj1, MessageChat *obj2) { NSDate *d1 = [formatter dateFromString:obj1.LastDate]; NSDate *d2 = [formatter dateFromString:obj2.LastDate]; NSLog(@"[d1 compare:d2] %ld",(long)[d1 compare:d2]); NSLog(@"[d2 compare:d1] %ld",(long)[d2 compare:d1]); return [d2 compare:d1]; // descending order }]; NSLog(@"%@",finalAssignedArray); 
  • Using finalCompleteArray MutableArray
  • Using MessageChat is a model class object.
  • Using obj1.LastDate is an Object Model Class Variable
0
source

All Articles