【问题标题】:Sorting Table date Objective-C排序表日期Objective-C
【发布时间】:2012-06-11 13:33:58
【问题描述】:

我有一个包含两列的表:日期和名称。 我使用此代码对元素进行排序:

-(id)tableView:(NSTableView *)aTableView

objectValueForTableColumn:(NSTableColumn *)aTableColumn
       row:(NSInteger)rowIndex {


NSDictionary *itemDictionary = [itemListArray objectAtIndex:rowIndex];

if (aTableColumn == itemName) 
    return [itemDictionary valueForKey:@"ItemNameBrowser"];
else if (aTableColumn == dateCare)
{   
    NSDate *date_to_set;
    if ([[itemDictionary valueForKey:@"ItemdateCare"] isKindOfClass:[NSString class]])
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setTimeStyle:NSDateFormatterMediumStyle]; 
        [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; 
        [dateFormatter setLocale:[NSLocale currentLocale]]; 

        date_to_set = [dateFormatter dateFromString:[itemDictionary valueForKey:@"ItemdateCare"]];
    }
    else
    {
        date_to_set = [itemDictionary valueForKey:@"ItemdateCare"];
    }

    return date_to_set;
}


else 

    return nil;

}



//sorting table view
-(void)tableView:(NSTableView *)tableView sortDescriptorsDidChange: (NSArray *)oldDescriptors 
{   

[itemListArray sortUsingDescriptors: [tableView sortDescriptors]];
[tableView reloadData];

}

-(void)addItem {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle]; 
[dateFormatter setLocale:[NSLocale currentLocale]];  



//Valori da aggiungere
NSString *newItemNameBrowser = @"Item";
NSString *newItemDateCare = [NSDate date];

NSMutableDictionary *newItem = [NSMutableDictionary dictionary];
[newItem setValue:newItemNameBrowser forKey:@"ItemNameBrowser"];
[newItem setValue:newItemDateCare forKey:@"ItemdateCare"];

[itemListArray addObject:newItem];
[tableList reloadData];

[dateFormatter release];

}

在 MainMenu.xib 中的列是:

Sort Key ItemName
Selector compare:

Sort Key ItemDate
Selector compare:

列名没问题。 问题是对日期列进行排序,因为没有正确重新排序日期。 元素仅被视为数字。

感谢您的帮助!

【问题讨论】:

    标签: objective-c macos sorting date nstableview


    【解决方案1】:

    我假设您将itemListArray 中的日期存储为字符串。不。将它们存储为 NSDates,然后它们将显示正确排序。

    您需要将 NSDateFormatter 附加到 NSTableColumn 文本字段单元格,以将它们转换为字符串以供查看。

    【讨论】:

    • 我添加了我的代码。我用这个: NSDate *newItemDate = [NSDate date];添加元素
    • 正如我所说,将日期存储为NSDates,而不是字符串。仅在需要显示的位置将它们转换为字符串,这可以通过文本字段单元格上的NSDateFormatter 自动完成。
    • 我更新了我的代码,现在它可以工作了,但不要使用 NSDateFormatterShortStyle。我想与 DD/MM/YYYY HH.MM.SS 约会。不明白哪里弄错了。你能帮助我吗?非常感谢。
    • @Joannes:您使用的是中等风格,而不是短风格。您使用的日期格式化程序是您在 table:objectValueForTableColumn: 中创建的,而不是在 addItem: 中创建的日期格式化程序
    • P:是的,我设置了 NSDateFormatterShortStyle 但“中欧夏令时间”仍然存在。我可以删除它吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 2013-03-18
    • 1970-01-01
    • 2012-01-24
    • 2016-05-06
    • 2020-06-20
    相关资源
    最近更新 更多