0

嗨,我有以下字典数组,我想使用键“BirthDate”对数组进行排序,我的代码如下

NSLog(@"nodeEventArray == %@", temp);
NSSortDescriptor *dateDescriptor = [NSSortDescriptor
                                    sortDescriptorWithKey:@"BirthDate"
                                    ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
NSArray *sortedEventArray = [temp
                             sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"sortedEventArray == %@", sortedEventArray);

但我无法正确排序,谁能告诉我如何根据“BirthDate”键对字典数组进行排序。因为出生日期是来自服务的字符串

字典样本数组:

   nodeEventArray = (
        {
        BirthDate = "05/04/1986";
        Email = "";
        FirstName = Test;
        IsSpouse = 0;
        LastName = Test;
        MiddleInitial = "";
        PatientID = "";
        Phone = "";
        ScacntronCSVId = 40409;
        SlotID = 1;
        UserName = "Tes_02192013010055";
    },
        {
        BirthDate = "02/14/1986";
        Email = "";
        FirstName = Guest;
        IsSpouse = 0;
        LastName = Guest;
        MiddleInitial = "";
        PatientID = "";
        Phone = "";
        ScacntronCSVId = 40410;
        SlotID = 2;
        UserName = "Gue_02192013014725";
    },
        {
        BirthDate = "02/17/1987";
        Email = "";
        FirstName = User;
        IsSpouse = 0;
        LastName = User;
        MiddleInitial = "";
        PatientID = "";
        Phone = "";
        ScacntronCSVId = 40411;
        SlotID = 3;
        UserName = "Use_02192013020726";
    }
    )
4

2 回答 2

1

我假设该数组来自服务器或其他东西(因此是“用户名”位),但仍然最好将每个用户/事件/任何内容存储在具有 NSDate 的对象中。这样,您只需按日期排序即可。

但是,如果您想对该数组进行排序,那么...

如果要按 BirthDate 排序(使用日期),则需要将字符串转换为实际的 NSDates。

NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateFormat = @"MM/dd/yyyy";

[blah sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
    NSDate *date1 = [df dateFromString:[obj1 objectForKey:@"BirthDate"];
    NSDate *date2 = [df dateFromString:[obj2 objectForKey:@"BirthDate"];

    return [date1 compare:date2];
}];

这应该这样做。

它将字符串转换为日期,然后进行比较。

于 2013-02-19T07:56:51.650 回答
0

您可以使用比较器而不是使用 sortDescriptor

NSArray *sortedArray = [nodeEventArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
        NSDateFormatter *dateFormator = [[NSDateFormatter alloc] init];
        NSDate *date1 = [dateFormator dateFromString:[[obj1 objectForKey:@"BirthDate"] stringByReplacingOccurrencesOfString:[[obj1 objectForKey:@"BirthDate"] lastPathComponent] withString:@"2013"]];
        NSDate *date2 = [dateFormator dateFromString:[[obj1 objectForKey:@"BirthDate"] stringByReplacingOccurrencesOfString:[[obj1 objectForKey:@"BirthDate"] lastPathComponent] withString:@"2013"]];
        if ([date1 earlierDate:date2] == date1) {
            return (NSComparisonResult)NSOrderedDescending;
        }else{
            return (NSComparisonResult)NSOrderedAscending;
        }

    }];
于 2013-02-19T07:56:41.463 回答