Sort NSArray of NSDictionaries by string date in key?

泪湿孤枕 提交于 2019-11-30 20:45:29

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);

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!