jason
jason

Reputation: 259

How to pass variable from tableview to second tableview?

I have a TableViewController with x rows. When the user taps on one row , i want to pass to the second tableViewController a variable that will determine which data the second tableViewController should load. How would I do that?

I am using Xcode 4.2, storyboard here's the code:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *__strong)indexPath
{
    // Navigation logic may go here. Create and push another view controller.

    TestTable *detail = [self.storyboard instantiateViewControllerWithIdentifier:@"TestTable"];

    [self.navigationController pushViewController:detail animated: YES];

    detail.num = [NSString stringWithFormat:[heads objectAtIndex:indexPath.row]];

In "heads" i get a number which i have to pass to the second tableview,depending upon which second tableview show data. Don't know whether the last line loads "heads" in "num". Is my approach correct? Any help/reference is appreciated

Upvotes: 2

Views: 2172

Answers (2)

jason
jason

Reputation: 259

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *__strong)indexPath {
    // Navigation logic may go here. Create and push another view controller.

    TestTable *detail = [self.storyboard instantiateViewControllerWithIdentifier:@"TestTable"];

    detail.num = [[NSString stringWithFormat:[heads objectAtIndex:indexPath.row]] intValue];
    [self.navigationController pushViewController:detail animated: YES];
}

Upvotes: 1

Marko
Marko

Reputation: 168

Give your TestTable a property for the variable you want to past, e.g.

@property (retain, nonatomic) NSNumber *myNumber;

in your didSelectRowAtIndexPath assign it like:

TestTable *detail = [self.storyboard instantiateViewControllerWithIdentifier:@"TestTable"];

// this assumes that you only have one section in your table
detail.myNumber = [NSNumber numberWithDouble:[heads objectAtIndex:indexPath.row]];

[self.navigationController pushViewController:detail animated: YES];

detail.num = [NSString stringWithFormat:[heads objectAtIndex:indexPath.row]];

In your second table's viewcontroller, you can use the number as follows:

double d = [self.myNumber doubleValue];

Upvotes: 2

Related Questions