Reputation: 7120
I am working on an iPad app where I deal with 2 controllers. My parent controller (say Controller A) has a cell which when clicked calls/navigates to child controller (say Controller B) through pushViewController as below:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
ControllerB *controllerB = [[ControllerB alloc] initWithStyle:UITableViewStyleGrouped];
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered
target:nil action:nil];
[self.navigationItem setBackBarButtonItem:backButton];
[self.navigationController pushViewController:controllerB animated:YES];
}
Now in ControllerB, I deal with a switch which has to maintain its state when the user navigates back and forth from ControllerB to ControllerA and then back to ControllerB i.e. User changes the switch state on ControllerB (eg:YES), goes back to ControllerA and then when comes back to ControllerB the user should see the same state of switch which he was on when he navigated back. (i.e:YES)
I am thinking to send back the state of the switch from ControllerB to ControllerA so that when ControllerB gets initialized again, the state of switch can be sent along to set the state of the switch.
Few design questions:
Upvotes: 0
Views: 175
Reputation: 104092
There's no need to involve controller A in this at all, just don't instantiate a new controller B every time you push to it. Create a property for controllerB, and check if the controller exists before you push it.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (! self.controllerB) {
self.controllerB = [[ControllerB alloc] initWithStyle:UITableViewStyleGrouped];
}
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered
target:nil action:nil];
self.navigationItem setBackBarButtonItem:backButton];
[self.navigationController pushViewController:self.controllerB animated:YES];
}
If you need to pass data back to controllerA from controllerB, for any reason, then you should use a delegate to do that (BTW, controllerB is not a child of controllerA. They're both children of the navigation controller, which makes them sibs).
Upvotes: 1
Reputation: 4856
I would save the state of the switch in a global object (a singleton may be a good option) or maybe CoreData or plist
if you need that to persist between app openings. To save that value you don't need to pass the info to the parent view controller, you can do it every time you change the state of the switch.
Anyway, if you have to pass data to your parent view controller, you should use delegates or you can send a notification through NSNotificationCenter
, but that's not very usual and I recommend using delegates instead.
Upvotes: 0