Sort NSArray of NSDictionaries by string date in k

2019-02-13 14:27发布

I have been struggling to find an easy way to sort an NSMutableArray that contains NSDictionaries. Each NSDictionary has a key named "Date" which contains an NSString of a date (ex: 10/15/2014).

What I am looking to do is sort the array based on those strings in ascending order.

I have 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 have 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 way results in a crash and I think it is because it is a NSString instead of a NSDate but I am just at a loss on how to do this.

Can anyone show me the correct way to accomplish this?

This is how I call the first block of code:

theDictionaries = [[theDictionaries sortedArrayUsingFunction:dateSort context:nil] mutableCopy];

2条回答
做个烂人
2楼-- · 2019-02-13 14:50

if you want to sort using Model Class then you must 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 is MutableArray
  • Using MessageChat is Object Model Class File
  • Using obj1.LastDate is Object Model Class Variable
查看更多
手持菜刀,她持情操
3楼-- · 2019-02-13 15:02

You need to get the strings inside your dictionaries. It looks like you're trying to compare the dictionaries themselves. If you had 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);
查看更多
登录 后发表回答