ace_ventura
ace_ventura

Reputation: 468

iOS 6 pass data from TableView to Detail View

I've a table view with some rows and each row has its Detail Disclosure button. I want that when the user taps on that button, another table view (customized by storyboard) appears and shows some relative data.

From TableViewController.m

-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {

    DetailViewController *detailViewController = [[detailViewController alloc] init];
    //creating a parse object
    PFObject *checkin = [_dataSourceArray objectAtIndex:indexPath.row];
    //getting data i want
    NSString *trainNumb = [checkin objectForKey:@"trainNumber"];
    //passing the data
    detailViewController.trainNumber = trainNumb;   
}

From the DetailTableViewController.m

- (void)viewDidLoad {
    [_trainNumberLabel setText:_trainNumber];
}

The problem is that in the DetailTableView the NSString results to be null.

What I'm missing here? Thank you!

Upvotes: 0

Views: 727

Answers (1)

Timothy Moose
Timothy Moose

Reputation: 9915

If this code actually compiles, this may be your problem:

DetailViewController *detailViewController = [[detailViewController alloc] init];

It should be:

DetailViewController *detailViewController = [[DetailViewController alloc] init];

But you shouldn't be alloc/initing your view controller in the first place. When you customize a view controller in Interface Builder, you've got to instantiate it like this if you want those customizations:

[self.storyboard instantiateViewControllerWithIdentifier:@"MyStoryboardIdentifier"]`

And you've got to set the controller's storyboard ID to "MyStoryboardIdentifier" or whatever identifier you want to use.

Also, as you've indicated in the comments, you've got a timing issue: your detail controller's viewDidLoad runs before you set the train number. A better approach would be to ensure that it works regardless of the sequence:

- (void)updateTrainNumberLabel
{
    self.trainNumberLabel.text = self.trainNumber;
}

- (void)setTrainNumber:(NSString *)trainNumber
{
    _trainNumber = trainNumber;
    [self updateTrainNumberLabel];
}

- (void)viewDidLoad
{
    ...
    [self updateTrainNumberLabel];
}

In other words, you configure your label in a separate method, in this case updateTrainNumberLabel, and when anything that could affect the label happens, e.g. the view loading or the number being changed, you call the method.

Upvotes: 1

Related Questions