排序字典数组

时间:2013-02-19 07:46:00

标签: iphone ios sorting

我有一个以下的字典数组,我想使用关键字“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";
    }
    )

2 个答案:

答案 0 :(得分: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];
}];

这应该这样做。

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

答案 1 :(得分: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;
        }

    }];