Sorting NSMutablearray by NSString as a date

匿名 (未验证) 提交于 2019-12-03 10:10:24

问题:

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?

回答1:

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 will be sorted but will have dictionary objects, each containing 2 strings.



回答2:

Quick and dirty fix - rearrange the string so that the date is first

str = [[str substringFromIndex:someIndex] stringByAppendingString:[str substringToIndex:someIndex]];

then just switch everything back once the array is sorted.



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