首页 文章

NSDate在NSMutableArray中对NSDictionaries进行排序

提问于
浏览
2

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

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

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

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

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

更新:

我已设法对日期进行排序,但我遇到了这个问题:在dicts中不仅有日期,还有其他对象,我的代码所做的只是切换日期值而不是切换完整的dicts周围 . 有了这个,dicts中的其他值被分配了错误的日期,这是非常糟糕的 . 有谁能够帮我?继承我的代码:

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

2 回答

  • 12

    有很多方法可以做到这一点,一种方法是使用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 = // create NSDate from dict1's Date;
        NSDate *date2 = // create NSDate from dict2's Date;
        return [date1 compare:date2];
    }];
    

    当然,这可能比第一种方法慢,因为您通常最终会创建超过n个NSDate对象 .

  • 0

    有几个选项,一个是将NSDate对象放入字典中 .

    比较字符串的一个问题是你不能只进行字符串比较,因为年份不是字符串中最重要的部分 .

    因此,您需要编写一个比较方法来使用:

    - (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr
    

    也许:

    - (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context
    

    比较器需要处理 dd.mm.yyyy hh:mm 字符串格式 .

    其他选项包括添加另一个带有NSDate表示的字典键并对其进行排序 .

相关问题