我有一个带有多个词典对象的数组,其中包含键Date
和Type
我想按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;
}
)
请帮帮我。我如何按日期按升序排列。
答案 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] ;