按NSString将NSMutablearray排序为日期 [英] Sorting NSMutablearray by NSString as a date

查看:97
本文介绍了按NSString将NSMutablearray排序为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,其中填充了字符串对象.在每个对象内是对象的名称和字符串,用-"分隔,例如. 对象1-26.05.2012".我想按字符串中的日期而不是名称对数组进行排序,这可能吗?

I have an array, which is filled out with string objects. Inside each object is the name of the object and the string, seperated by " - ", ex. "Object1 - 26.05.2012 ". I would like to sort my array by the date in the string, and not the name, descending Is this possible?

推荐答案

正如@Vladimir指出的那样,最好将名称和字符串彼此分开并按日期排序.

As @Vladimir pointed out, it would be much better to separate the name and the string from each other and sort by the date.

NSMutableArray *newArray = [[NSMutableArray alloc] init];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd.MM.yyyy"];
for (NSString *str in yourArray)
{
    NSRange rangeForDash = [str rangeOfString:@"-"];
    NSString *objectStr = [str substringToIndex:rangeForDash.location];
    NSString *dateStr = [str substringFromIndex:rangeForDash.location+1];
    NSDate *date = [formatter dateFromString:dateStr];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:objectStr, @"object", date, @"date", nil];
    [newArray addObject:dic];
}
NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO];
[newArray sortUsingDescriptors:[NSArray arrayWithObjects:sortDesc, nil]];
[sortDesc release];
[formatter release];

newArray将进行排序,但将具有字典对象,每个对象包含2个字符串.

newArray will be sorted but will have dictionary objects, each containing 2 strings.

这篇关于按NSString将NSMutablearray排序为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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