按键字符串日期对NSDictionaries的NSArray进行排序? [英] Sort NSArray of NSDictionaries by string date in key?

查看:124
本文介绍了按键字符串日期对NSDictionaries的NSArray进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力寻找一种简单的方法来排序包含NSDictionaries的NSMutableArray。每个NSDictionary都有一个名为Date的键,其中包含一个日期的NSString(例如:10/15/2014)。

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
}

我也尝试过没有运气:

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

每种方式都会导致崩溃,我认为这是因为它是NSString而不是NSDate,我如何做到这一点我都感到失落。

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


推荐答案

您需要在字典中找到字符串。看起来你正在试图比较自己的字典。如果你有一个叫做数据的数组,你会做这样的事情,

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

这篇关于按键字符串日期对NSDictionaries的NSArray进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆