David
David

Reputation: 2620

UITableViewController didSelectRowAtIndexPath:(NSIndexPath *)indexPath

How can I reference the cell object that was clicked inside the didSelectRowAtIndexPath:(NSIndexPath *)indexPath method?

I have a UISplitViewController, and in the MasterView I have a table, with cells where cell.tag = a primary key from a sqlite database (i.e. table is populated from db). I'm able to capture the click event in the above method, but I can't see how I can pass the cell object in, or how I can otherwise reference it to get at cell.tag. Ultimately, the goal is to pass that id to the detail view via the Master/Detail delegate, and then load data into the DetailView based on the id that comes in from the Master.

Any tips are appreciated!

Edit:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.
    cell.textLabel.text = NSLocalizedString(@"Detail", @"Detail");
    Entry *entry = [self.entries objectAtIndex:[indexPath row]];
    [[cell textLabel] setText:[NSString stringWithFormat:@"%@",entry.title]];
    cell.tag = entry.entryID;
    return cell;
}

Upvotes: 0

Views: 4479

Answers (4)

bhagyavendra
bhagyavendra

Reputation: 5

You can it by save all id in NSMutableArray and then pass in by this method in an other class..

classInstanceName.IntVariableName=[[taskIdArray objectAtIndex:indexPath.row]intValue]

Upvotes: 0

hoshi
hoshi

Reputation: 1707

Because you already have an array of entries, you can also write as follows.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    Entry *entry = [self.entries objectAtIndex:[indexPath row]];
}

I think this is preferred way than cellForRowAtIndexPath: because

  • you can get the whole entry object, not only the ID.
  • you can use non-integer ID like string.
  • you don't depend on table or cell (decoupling).

Upvotes: 4

aopsfan
aopsfan

Reputation: 2441

In didSelectRowAtIndexPath:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
}

Note how asking the table for cellForRowAtIndexPath: returns a cell, whereas asking the controller for tableView:cellForRowAtIndexPath: runs the delegate method.

Upvotes: 4

Nathanial Woolls
Nathanial Woolls

Reputation: 5291

You can use the method cellForRowAtIndexPath to get the UITableViewCell from the NSIndexPath.

Upvotes: 2

Related Questions