我有一个包含 NSDictionary 对象的数组,其中一个键是 Time,它包含像“2013-10-09”这样的时间字符串格式,我需要按 Time 键对数组进行排序,但我不知道如何排序 NSString用那种格式。
问问题
187 次
3 回答
0
- (void)testSortTimeAsString {
NSDictionary *dict1 = @{@"key" : @"none", @"Time" : @"2013-10-01", @"optional" : @"---"};
NSDictionary *dict2 = @{@"key" : @"none", @"Time" : @"2012-12-21", @"optional" : @"---"};
NSDictionary *dict3 = @{@"key" : @"none", @"Time" : @"2013-02-10", @"optional" : @"---"};
NSDictionary *dict4 = @{@"key" : @"none", @"Time" : @"2013-11-25", @"optional" : @"---"};
NSDictionary *dict5 = @{@"key" : @"none", @"Time" : @"2013-06-15", @"optional" : @"---"};
NSArray *array = @[dict1, dict2, dict3, dict4, dict5];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd";
NSArray *sorted = [array sortedArrayWithOptions:0 usingComparator:^(id obj1, id obj2) {
NSString *stringDate1 = obj1[@"Time"];
NSString *stringDate2 = obj2[@"Time"];
NSDate *date1 = [dateFormatter dateFromString:stringDate1];
NSDate *date2 = [dateFormatter dateFromString:stringDate2];
NSComparisonResult result = [date1 compare:date2];
return result;
}];
NSLog(@"Sorted array: \n%@", sorted);
}
于 2013-10-22T07:02:30.577 回答
0
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSMutableArray *dates = [NSMutableArray arrayWithCapacity:datesAry.count];
for (NSString *dateString in dates)
{
NSDate *date = [dateFormatter dateFromString:timeString];
[dates addObject:date];
}
[dates sortUsingSelector:@selector(compare:)];
NSMutableArray *sortedDates= [NSMutableArray arrayWithCapacity:dates.count];
for (NSDate *date in dates)
{
NSString *dateString = [dateFormatter stringFromDate:date];
[sortedDates addObject: dateString];
}
于 2013-10-22T06:58:00.283 回答
0
使用该格式对日期进行排序与将它们排序为字符串具有相同的结果。所以:
NSArray *unordered = @[
@{ @"Time": @"2001-01-01", @"Place" : @"Somewhere" },
@{ @"Time": @"1999-01-01", @"Place" : @"Elsewhere" },
@{ @"Time": @"1999-02-01", @"Place" : @"Nowhere" }
];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"Time" ascending:YES selector:@selector(compare:)];
NSArray *ordered = [unordered sortedArrayUsingDescriptors:@[ sortDescriptor ]];
会给你排序的数组。
于 2013-10-22T08:33:21.817 回答