Ameya Vaidya
Ameya Vaidya

Reputation: 127

Getting the index of the selected row

I have an app where a user clicks a row in a TableViewController and then on another view controller, it displays some information. Right now the information only displays for the objectAtIndex: 0. I want it so that I can get the object for the row the user selects.

TableViewController:

static NSString *cellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

NSManagedObjectModel *playerModel = [self.playersArray objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:@"%@ vs %@", [playerModel valueForKey:@"player1"], [playerModel valueForKey: @"player2"]]];
[cell.detailTextLabel setText:[playerModel valueForKey:@"date"]];

return cell;

ViewController:

NSManagedObjectContext *managedObjectContext = [self managedObjectContext];

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:@"Match"];

self.playersArray = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];


NSManagedObjectModel *playerModel = [self.playersArray objectAtIndex: 0];

UILabel *location = [[UILabel alloc]initWithFrame:CGRectMake(20, 130, 300, 20)];
[location setText:[NSString stringWithFormat:@"Games: %@", [playerModel valueForKey:@"location"]]];
[self.view addSubview:location];

The TableViewController works fine but as I said above, only the objectAtIndex: 0 shows above.

Upvotes: 1

Views: 147

Answers (3)

Gal Marom
Gal Marom

Reputation: 8629

You can inspect the selected index and get the row from it:

[[self.tableView indexPathForSelectedRow] row];

Upvotes: 0

JonEasy
JonEasy

Reputation: 1013

Since your other ViewController can't access the tableView of the TableViewController directly in your implementation (i suppose), you have to actually transfer your model object to your ViewController. How depends on your implementation, i.e. whether you are using storyboards or not.

In any case I'd advice to define a public property for ViewController for the NSManagedObject you want to transfer.

If your using storyboards you can set this property in prepareForSegue:, if your not using storyboards then before presenting the ViewController set this property to your model object.

Upvotes: 1

ekscrypto
ekscrypto

Reputation: 3806

There are a couple ways of handling this. You can setup a UITableView delegate, and implement -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath or you can call the UITableView method [myTableVie indexPathForSelectedRow]

Upvotes: 0

Related Questions