Abid Mehmood
Abid Mehmood

Reputation: 145

How to pass an object by reference from one class to other class?

I an initialising a new view controller by tapping the cell of current controller. All I want to pass the object at cell to next controller by reference so that if I change the object in new controller it should change at original place.

I have tried much to get answer about it but could not get anywhere.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString * storyboardName = @"Main";
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
    RecentItemDetailViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"RecentItemDetailViewController"];

    vc.station = self.stations[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}

All I want to get self.stations[indexPath.row] object in vc.station by reference so if I change vc.station then self.stations[indexPath.row] should also be changed.

self.stations and vc.station both are NSMutableArray type.

Upvotes: 0

Views: 42

Answers (1)

Matic Oblak
Matic Oblak

Reputation: 16774

You already did it correctly. What you are most likely missing is reloading table view when you come back.

You can override view will appear method. Then check what is the selected row on your table view. Reload that row.

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    if(self.tableView.indexPathForSelectedRow) {
        [self.tableView reloadRowsAtIndexPaths:@[tableView.indexPathForSelectedRow] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    }

    // Or just reload  the whole thing
    [self.tableView reloadData];
}

But this naturally assumes you are never ever assigning to station property inside the RecentItemDetailViewController. You can call things like [self.station add...] but never self.station = ....

Upvotes: 2

Related Questions