简体   繁体   English

按NSDate对NSTableColumn进行排序

[英]Sort NSTableColumn by NSDate

I have table in table there is a column with dates in format of dd/MM/yy the entries are in NSString , now after clicking on the column header ie sort Descriptor icon column should get sort ascending or descending depending on sort Descriptor. 我在表中的表中有一列,其日期为dd/MM/yy ,日期为NSString ,现在在单击列标题后,即sort Descriptor图标列应根据升序Descriptor升序或降序。 In present its sorting in numeric order for example like 目前,其以数字顺序排序例如

  1. 10/23/13 13年10月23日
  2. 11/4/09 09年11月4日
  3. 5/2/06 06年5月2日

But I want the columns should have sorted by date: 但是我希望这些列应该按日期排序:

  1. 5/2/06 06年5月2日
  2. 11/4/09 09年11月4日
  3. 10/23/13 13年10月23日

I have written following code 我写了下面的代码

- (void)tableView:(NSTableView *)tableView sortDescriptorsDidChange:(NSArray *)oldDescriptors
{
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
    [fifiMainList sortUsingComparator:^NSComparisonResult(id a, id b) {

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat: @"yyyy MM dd"];

    NSString *date1String = [a valueForKey:@"date"];
    NSString *date2String = [b valueForKey:@"date"];

    NSDate *date1 = [dateFormat dateFromString:date1String];
    NSDate *date2 = [dateFormat dateFromString:date2String];
    return [date1 compare:date2];
    }];
}

But it's not working for me. 但这对我不起作用。

Do I need to write sorting code in sortDescriptorsDidChange or somewhere else? 我是否需要在sortDescriptorsDidChange或其他地方编写排序代码? and I also need sortDescriptorsDidChange method in my project. 并且我的项目中还需要sortDescriptorsDidChange方法。

Try like this :- 尝试这样:-

NSArray *yourArr=[NSArray arrayWithObjects:@"10/23/13",@"11/4/09",@"5/2/06",nil];
NSDateFormatter *format=[[[NSDateFormatter alloc]init]autorelease];
[format setDateFormat:@"dd/mm/yy"];
NSMutableArray *arr2=[NSMutableArray array];
for (NSString *str in yourArr)
{
    [arr2 addObject:[format dateFromString:str]];
}
    NSLog(@"Before=%@",arr2);
[self.arr sortUsingSelector:@selector(compare:)];
    NSLog(@"After=%@",self.arr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM