0

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

-(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:

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

在此处输入图像描述

感谢帮助!

4

1 回答 1

0

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

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

于 2012-06-11T13:43:46.110 回答