如何在Array中的多个Dictionary中按升序创建数组

时间:2016-09-07 11:21:37

标签: ios objective-c arrays sorting dictionary

我有一个带有多个词典对象的数组,其中包含键DateType 我想按Date键按升序排列数组。

My Array喜欢这个:

(
{
    Date = "06 September 2016";
    Type = Photo;
},
    {
    Date = "06 September 2016";
    Type = Video;
},
    {
    Date = "07 September 2016";
    Type = Photo;
},
    {
    Date = "07 September 2016";
    Type = Video;
},
    {
    Date = "06 September 2016";
    Type = Photo;
},
    {
    Date = "06 September 2016";
    Type = Photo;
},
    {
    Date = "07 September 2016";
    Type = Photo;
},
{
    Date = "01 October 2016";
    Type = Photo;
},
{
    Date = "06 September 2016";
    Type = Photo;
    }
)

请帮帮我。我如何按日期按升序排列。

2 个答案:

答案 0 :(得分:3)

您需要像这样使用sortedArrayUsingComparator来使用String对日期进行排序。首先使用NSDate将日期从字符串转换为NSDateFormatter,然后进行比较。

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

答案 1 :(得分:1)

试试这个

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Date"ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; 
NSArray *sortArray = [YourArray sortedArrayUsingDescriptors:sortDescriptors] ;