排序字典数组 [英] sorting array of dictionaries

查看:155
本文介绍了排序字典数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

HI i have a following array of dictionaries and and i want to sort the array using the the key "BirthDate" and my code is as follows

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

但我无法正确排序任何人请告诉我如何排序基于字典的数组在BirthDate键上。自出生日期即将来自服务

but I was unable to sort properly can any one please tell me how to sort the array of dictionary based on "BirthDate" key .Since birth date is coming as string from service

样本数组:

   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";
    }
    )


推荐答案

使用sortDescriptor你可以使用比较器

Instead of using sortDescriptor you can use comparator

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;
        }

    }];

这篇关于排序字典数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆