如何在cocoa中按tableview的列排序

如何在cocoa中按tableview的列排序,cocoa,tableview,Cocoa,Tableview,我的应用程序中有一个tableview。它有两列,一列是“键”,一列是“值”,tableview的代码如下: - (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView { //DataEntity *dataEntity = [[DataEntity alloc]init]; return [dataEntity.items count]; } - (id)tableView:(NSTableView *)tab

我的应用程序中有一个tableview。它有两列,一列是“键”,一列是“值”,tableview的代码如下:

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
    //DataEntity *dataEntity = [[DataEntity alloc]init];
    return [dataEntity.items count];
}

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    //DataEntity *dataEntity = [[DataEntity alloc]init];
    if([[tableColumn identifier]isEqualToString:@"key"])
    {
        return [[dataEntity.items allKeys] objectAtIndex:row];
    }
    if([[tableColumn identifier] isEqualToString:@"value"])
    {
        return [[dataEntity.items allValues] objectAtIndex:row];
    }
    return nil;
}
dataEntity是数据源的单一实例,items是可变字典。现在我想在单击一列的标题后按该列进行排序。如何实施? 我试着按照下面的方法做,但不起作用

-(void)tableView:(NSTableView *)tableView mouseDownInHeaderOfTableColumn:(NSTableColumn *)tableColumn
{
    NSImage *indicatorImage;
    if(sortAscending)
    {
    indicatorImage = [NSImage imageNamed:@"NSAscendingSortIndicator"];
    NSMutableDictionary *tempDict = [[NSMutableDictionary alloc]init];
    [tempDict setDictionary:dataEntity.items];
        NSLog(@"before sort %@",tempDict);
    NSArray *keys =  [tempDict allKeys];
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1,id obj2){
        return ([obj1 compare:obj2 options:NSNumericSearch]);
    }];

    [dataEntity.items setDictionary:tempDict];

    }
    else
    {
    indicatorImage = [NSImage imageNamed:@"NSDescendingSortIndicator"];
    }
    sortAscending=!sortAscending;
    [tableView setIndicatorImage:indicatorImage inTableColumn:tableColumn];
    [tableView reloadData];
}

实现这一点的最简单方法是通过IB,只需选择表列和属性检查器,然后将“排序键”设置为表示字典中的值的属性