简体   繁体   中英

sorting NSMutableArray contain NSArray using sortedArrayUsingComparator

I got problem for sorting array of nsdate. so i have array of date inside nsmutablearray

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSArray *arrString = [[NSArray alloc] initWithObjects:@"2012-05-01", @"2012-02-01", @"2012-22-03", @"2012-05-01", @"2012-15-01", nil];
NSMutableArray *arrDate = [[NSMutableArray alloc] initWithCapacity:arrString.count];
for (NSString *item in arrString) {
    NSDate *date = [dateFormatter dateFromString:item];
    [arrDate addObject:date];
}

as i saw in many cases they use code like this to sort array:

NSArray *sortedArray = [arrDate sortedArrayUsingComparator:^(id firstObject, id secondObject) {
    return [((NSDate *)firstObject) compare:((NSDate *)secondObject)];
}];

i tried to put my array on it, but not worked. Anyone can help me how actully best way to sort nsmutablearray contain nsdate. I want to put the latest date at top of the index array.

So the real question is, how can i sort data inside arrDate?

Thank you.

Your date format does not match the date strings you are using.

yyyy-MM-dd hh:mm:ss

means the dates you supply should look something like:

2012-05-09 15:54:21
        ^^ Day
     ^^ Month

ie your strings are missing the hours, minutes and seconds and you have some dates with month 22 and month 15. If a date formatter can't parse a date, I think it returns nil which would mean you are trying to put nil into an array, which will cause an exception.

Edit

To actually sort the dates, your sample code looks OK except that you want most recent first, so reverse the compare:

NSArray *sortedArray = [arrDate sortedArrayUsingComparator:^(id firstObject, id secondObject) {
     return [secondObject compare: firstObject];
}];   

Or with a mutable array, you can sort in place:

[arrDate sortUsingComparator:^(id firstObject, id secondObject) {
     return [secondObject compare: firstObject];
}];    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM