Rob
Rob

Reputation: 15992

UITableView : popViewController and keep row index into parent controller?

I have the following config :

A ViewController parentController containing a TableView parentTable with customized cells to display 2 labels in each of them.

A ViewController childController containing a TableView childTable. This view is displayed when the user clicks a cell of controllerParent, and childTable content depends on the selected parentController cell. I use this method :

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

Now when I click a cell in childTable, I come back to my previous view with this :

[self.navigationController popViewControllerAnimated:YES];

Of course I can easily get the index of the childTable's row selected. But the only thing I don't know is how to keep this data to use it in parentController when I come back there ?

Thanks for your help...

Upvotes: 3

Views: 1339

Answers (1)

Pfitz
Pfitz

Reputation: 7344

For this kind of problem you can use delegation

Code from RayWenderlichs Tutorial:

.h in your childViewController:

@class ChildViewController;

@protocol ChildViewControllerDelegate <NSObject>
- (void)childViewControllerDidSelect:(id)yourData;
@end

@interface childViewController : UITableViewController

@property (nonatomic, weak) id <ChildViewControllerDelegate> delegate;

- (IBAction)cancel:(id)sender;
- (IBAction)done:(id)sender;

@end

.m in childViewController

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 [self.delegate childViewControllerDidSelect:myObject];
 [self.navigationController popViewControllerAnimated:YES];
}

in your parentViewController.h adopt the protocol

@interface ParentViewController : UITableViewController <ChildViewControllerDelegate>

and implement the delegate methods

- (void)childViewControllerDidSelect:(id)yourData 
{
    self.someProperty = yourData
}

and don't forget to set the delegate before pushing :

...
ChildViewController *vc  = [ChildViewController alloc] init];
vc.delegate = self;
[self.navigationController pushViewController:vc animated:YES];

Here is some docu about the delegation pattern: Delegates and Data Sources

Upvotes: 3

Related Questions