Objective-C排序字符串日期数组 [英] Objective-C Sort String Date Array

查看:139
本文介绍了Objective-C排序字符串日期数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,由日期组成,但 NSString 。如何排序?

I have an array which consists of dates but as NSString. How do I sort it descending?

编辑:我通过调整我的代码使用NSDate使用其他方法不会在我的情况下工作

EDIT : I Ended up by tweaking my code to use NSDate as using other methods won't work in my case

推荐答案

您可以使用 sortedArrayUsingFunction ,考虑下面的例子

You could use sortedArrayUsingFunction, consider the bellow example

NSString *str1 = @"03-07-2012";
NSString *str2 = @"01-07-2012";
NSString *str3 = @"02-07-2012";


NSArray *arr = [NSArray arrayWithObjects:str1, str2, str3, nil];
arr = [arr sortedArrayUsingFunction:dateSort context:nil];


//The date sort function
NSComparisonResult dateSort(NSString *s1, NSString *s2, void *context) {

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MM-yyyy"];

    NSDate *d1 = [formatter dateFromString:s1];
    NSDate *d2 = [formatter dateFromString:s2];

    return [d1 compare:d2]; // ascending order
    return [d2 compare:d1]; // descending order
}

这篇关于Objective-C排序字符串日期数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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