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.