2014-11-14 24 views
0

在我的應用程序中有一個tableview。它有2個列,一個是「鍵」和一個是「值」,爲的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是數據源和物品的一個勁兒地實例是一個可變dictianary。現在,我想按一列後排序該列的標題。如何實現它? 我試着按照下面的方式去做,但它不起作用。

-(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]; 
} 

回答

0

實現這一目標是通過IB,只需選擇表格列和屬性檢查器中,然後將「排序鍵」,以表示在你的字典和屬性值的最簡單方法。

enter image description here

相關問題