NSDate对NSMutableArray中的NSDictionaries进行排序 [英] Sort NSDictionaries in NSMutableArray by NSDate

查看:139
本文介绍了NSDate对NSMutableArray中的NSDictionaries进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSMutableArray与字典,所有的dict包含一个NSDate是NSString的形式与键'日期'。我想按日期排序NSDictionaries。例如,我有以下状态的数组:

  Dict 
日期
20.06.1996 23 :30
Dict
Date
04.10.2011 19:00
Dict
日期
20.06.1956 23:39



我想对它进行排序,看起来像这样:

  Dict 
日期
20.06.1956 23:39
Dict
日期
20.06.1996 23:30

日期
04.10.2011 19:00

我已经尝试过NSSortDescriptor ,但没有成功...



更新:



我设法排序日期,到这个问题:在dicts不仅有日期,还有其他对象,我的代码做的是它只切换日期值之间的日志,而不是切换完整的日期。这样,日记中的其他值被分配错误的日期,这是非常糟糕的。有谁能够帮助我? Heres我的代码:

  NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); 
NSString * documentsDirectory = [paths objectAtIndex:0];
NSString * path = [documentsDirectory stringByAppendingPathComponent:@savedData.daf];
NSMutableArray * d = [NSMutableArray arrayWithContentsOfFile:path];



for(int ii = 0; ii< [d count]; ii ++){
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
if(is24h){
[dateFormatter setDateFormat:@dd.MM.yyyy HH:mm];
}
else {
[dateFormatter setDateFormat:@dd.MM.yyyy hh:mm a];
}
[dateFormatter setLocale:[NSLocale currentLocale]];
NSDate * dat = [dateFormatter dateFromString:[[d valueForKey:@Date] objectAtIndex:ii]];
NSMutableDictionary * newDict = [[NSMutableDictionary alloc] init];
NSDictionary * oldDict =(NSDictionary *)[d objectAtIndex:ii];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:dat forKey:@Date];
[d replaceObjectAtIndex:ii withObject:newDict];
[newDict release];
}


NSSortDescriptor * sorter = [[NSSortDescriptor alloc] initWithKey:@Dateascending:YES];
NSArray * sorters = [[NSArray alloc] initWithObjects:sorter,nil];
[分拣机发布];
NSMutableArray * sorted = [NSMutableArray arrayWithArray:[d sortedArrayUsingDescriptors:sorters]];
[分类]
NSLog(@%@,sorted);
for(int ii = 0; ii <[sorted count]; ii ++){
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
if(is24h){
[dateFormatter setDateFormat:@dd.MM.yyyy HH:mm];
}
else {
[dateFormatter setDateFormat:@dd.MM.yyyy hh:mm a];
}
[dateFormatter setLocale:[NSLocale currentLocale]];
NSString * sr = [dateFormatter stringFromDate:[[sorted valueForKey:@Date] objectAtIndex:ii]];
NSMutableDictionary * newDict = [[NSMutableDictionary alloc] init];
NSDictionary * oldDict =(NSDictionary *)[d objectAtIndex:ii];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:sr forKey:@Date];
[sorted replaceObjectAtIndex:ii withObject:newDict];
[newDict release];
}
NSLog(@before:%@

after:%@,d,sorted);
[sorted writeToFile:path atomically:YES];


解决方案

有很多方法可以做到这一点,使用NSDate对象而不是NSStrings(或根据ISO 8601格式化的NSStrings,以使词典排序匹配期望的排序)。然后你可以这样做:

  NSSortDescriptor * descriptor = [NSSortDescriptor sortDescriptorWithKey:@Date
ascending:YES];
[array sortUsingDescriptors:[NSArray arrayWithObject:descriptor]];

或者,如果您不能(或不想)更改数据,总是使用块排序:

  [array sortUsingComparator:^(id dict1,id dict2){
NSDate * date1 = //从dict1的Date创建NSDate;
NSDate * date2 = //从dict2的Date创建NSDate;
return [date1 compare:date2];
}];

当然,这可能会比第一种方法慢,因为你通常会创建多于 NSDate对象。


I have a NSMutableArray with dictionaries, all of the dict's contain a NSDate is form of NSString with key 'Date'. I want to sort the NSDictionaries by the Dates. So for example i have the following state of the array:

Dict
   Date
      20.06.1996 23:30
Dict
   Date
      04.10.2011 19:00
Dict
   Date
      20.06.1956 23:39

And I want to sort it, so that it looks like this:

Dict
   Date
      20.06.1956 23:39
Dict
   Date
      20.06.1996 23:30
Dict
   Date
      04.10.2011 19:00

I have already experimented with NSSortDescriptor, but without success...

Update:

I have managed to sort the dates, but I came to this problem: In the dicts there is not only dates, also other objects, and what my code does is it only switches the date values between the dicts, instead of switching the complete dicts around. With this, the other values in the dicts get assigned a wrong date, which is very bad. Can anybody help me? Heres my code:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"savedData.daf"];
NSMutableArray *d = [NSMutableArray arrayWithContentsOfFile:path];



for (int ii = 0; ii < [d count]; ii++) {
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    if (is24h) {
        [dateFormatter setDateFormat:@"dd.MM.yyyy HH:mm"];
    }
    else {
        [dateFormatter setDateFormat:@"dd.MM.yyyy hh:mm a"];
    }
    [dateFormatter setLocale:[NSLocale currentLocale]];
    NSDate *dat = [dateFormatter dateFromString:[[d valueForKey:@"Date"] objectAtIndex:ii]];
    NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
    NSDictionary *oldDict = (NSDictionary *)[d objectAtIndex:ii];
    [newDict addEntriesFromDictionary:oldDict];
    [newDict setObject:dat forKey:@"Date"];
    [d replaceObjectAtIndex:ii withObject:newDict];
    [newDict release];
}


NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"Date" ascending:YES];
NSArray *sorters = [[NSArray alloc] initWithObjects:sorter, nil];
[sorter release];
NSMutableArray *sorted = [NSMutableArray arrayWithArray:[d sortedArrayUsingDescriptors:sorters]];
[sorters release];
NSLog(@"%@",sorted);
for (int ii = 0; ii < [sorted count]; ii++) {
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    if (is24h) {
        [dateFormatter setDateFormat:@"dd.MM.yyyy HH:mm"];
    }
    else {
        [dateFormatter setDateFormat:@"dd.MM.yyyy hh:mm a"];
    }
    [dateFormatter setLocale:[NSLocale currentLocale]];
    NSString *sr = [dateFormatter stringFromDate:[[sorted valueForKey:@"Date"] objectAtIndex:ii]];
    NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
    NSDictionary *oldDict = (NSDictionary *)[d objectAtIndex:ii];
    [newDict addEntriesFromDictionary:oldDict];
    [newDict setObject:sr forKey:@"Date"];
    [sorted replaceObjectAtIndex:ii withObject:newDict];
    [newDict release];
}
NSLog(@"before: %@"
      ""
      "after: %@",d,sorted);
[sorted writeToFile:path atomically:YES];

解决方案

There are many ways to do this, one would be to use NSDate objects instead of NSStrings (or NSStrings formatted according to ISO 8601, so that the lexicographic sort would match the desired sorting). Then you could do:

NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"Date" 
                                                             ascending:YES];
[array sortUsingDescriptors:[NSArray arrayWithObject:descriptor]];

Or, if you can't (or don't want to) change your data, you can always sort using a block:

[array sortUsingComparator:^(id dict1, id dict2) {
    NSDate *date1 = // create NSDate from dict1's Date;
    NSDate *date2 = // create NSDate from dict2's Date;
    return [date1 compare:date2];
}];

Of course this would probably be slower than the first approach since you'll usually end up creating more than n NSDate objects.

这篇关于NSDate对NSMutableArray中的NSDictionaries进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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