简体   繁体   中英

Sort NSDate objects in NSMutableArray using NSSortDescriptor?

In my project, I'm getting some data from an APi and I retreive the data into a NSMutableArray by parsing the JSON . It has a key called " StartDate " which is of the format : " mm/dd/yyyy hh:mm:ss " as shown below

StartDate: "5/18/2013 12:00:00 AM"

I'm saving these data to a resultArray .There are also 4 more keys for an object as my JSON is of the form

{
    EventId: "xxxx",
    Title: "xxx",
    Location: "xxxx",
    StartDate: "5/18/2013 12:00:00 AM",
    Link: null
}

there are multiple such objects here. All that I need to do is to sort the contents of the resultArray based on date(either ascending or descending), I use the following code

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"StartDate" ascending:TRUE];
[resultArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

But I;m getting a shuffled result, the sorting is not correct throughout, can anyone tel me where I had gone wrong .

Thanks

Should work

[resultArray sortUsingComparator:^NSComparisonResult(id a, id b) {

    static NSDateFormatter *dateFormatter = nil;

    if (!dateFormatter) {
        dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"mm/dd/yyyy hh:mm:ss"; 
    }

    NSString *date1String = [a valueForKey:@"StartDate"];
    NSString *date2String = [b valueForKey:@"StartDate"];

    NSDate *date1 = [dateFormatter dateFromString:date1String];
    NSDate *date2 = [dateFormatter dateFromString:date2String];

    return [date1 compare:date2];
}];

你的StartDate似乎是字符串格式,我相信它为字符串改组它。你应该首先转换为NSDate,然后应用这个描述符......希望这会有所帮助。

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