使用键值对NSMutableArray进行排序

时间:2016-07-26 11:51:16

标签: ios objective-c sorting

我低于NSMutableArray

我想根据 DOBDate 按升序排序数组元素

按字母顺序按名称键排序。

myarraytosort":[  
    {“DOBDate":"Jul 18, 1987”,”Name”:”Aman Singh”},
    {“DOBDate”:”Dec 18, 2000”,”Name”:”Dman Kumar”},
    {“DOBDate”:”June 18, 1990”,”Name”:”Cman Singh”},
    nil
]

代码我尝试但不工作

表示DOBDate

 NSSortDescriptor *dateDescriptor = [NSSortDescriptor
                                            sortDescriptorWithKey:@"DOBDate"
                                            ascending:NO];
        NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
        NSArray *sortedEventArray = [myarraytosort
                                     sortedArrayUsingDescriptors:sortDescriptors];
        NSLog(@"sortedEventArray == %@", sortedEventArray);

字母

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

1 个答案:

答案 0 :(得分:1)

您的DOBDate键包含字符串格式中的日期,因此您需要使用Comparator这样的方式对日期进行排序

NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"MMM dd, yyyy"];
NSArray *sortedArray = [yourArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
    NSDate *d1 = [df dateFromString:(NSString*) [obj1 valueForKey:@"DOBDate"]];
    NSDate *d2 = [df dateFromString:(NSString*) [obj2 valueForKey:@"DOBDate"]];
    return [d1 compare: d2];
}];