Search code examples
cocoaosx-mountain-lion

Working with two tables - how to get the correct rows


I have two cell-based tableviews (items and categories). I'm trying to get the correct row index for each so I can work with their arrays.

My code so far is this:

- (id) tableView:(NSTableView *)tableView
objectValueForTableColumn:(NSTableColumn *)tableColumn
         row:(NSInteger)row {
    //NSLog(@"%s", __FUNCTION__);

    if (tableView.tag == 0) {
        currentItem = [itemMutableArray objectAtIndex:row];
        NSString *itemTitle1 = [currentItem valueForKey:@"title"];
        return itemTitle1;
    } else {
        currentCategory  = [categoryMutableArray objectAtIndex:row];
        NSString *catName = [currentCategory valueForKey:@"name"];
        NSLog (@"currentCategory is %@", catName);
        return catName;
    }
}

but for each table, this returns something like :

 currentCategory is Cat One
 currentCategory is Cat Three
 currentCategory is Cat One
 currentCategory is Cat Three
 currentCategory is Cat One
 currentCategory is Cat Three
 currentCategory is Cat Two
 currentCategory is Cat One
 currentCategory is Cat Three
...

Am I using the wrong method, or what? Thanks.


Solution

  • If you have multiple tables in a same controller, its a good idea to have outlets for them.

    Then you can use as:

    - (id) tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    
        if(tableView==myFirstTableViewOutlet){
          .....
        }
        else if(tableView==mySecondTableViewOutlet){
          .....
        }
    }