Sort NSDictionaries in NSMutableArray by NSDate

我的未来我决定 提交于 2019-12-06 13:23:43

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.

There are a couple of options, one is to put NSDate objects in the dictionary.

One problem with comparing the strings is that you can 't just do a string compare because the year is not in the most significant potion of the string.

So, you will need to write a comparison method to use with:

- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr

or perhaps:

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

The comparator will need to handle the dd.mm.yyyy hh:mm string format.

Other options include adding another dictionary key with an NSDate representation and sorting on that.

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