Jack
Jack

Reputation: 151

ModalViewController to retain value

From the modalViewController (UniversitiesViewController *), I've tried to set a variable in the rootViewController with no luck. In my tableview:didSelectRowAtIndexPath: method I use the following code to set the rootViewController (MapsViewController *) selectedIndex property:

MapsViewController *mapsView = (MapsViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"MapsView"];
mapsView.selectedIndex = [NSNumber numberWithInt:indexPath.row];

[self dismissModalViewControllerAnimated:YES];

When I print the value of self.selectedIndex in the MapViewController it is always 0, which is not the value selected.

Thanks in advance for your help.

Upvotes: 1

Views: 49

Answers (1)

Hampus Nilsson
Hampus Nilsson

Reputation: 6822

The correct way to do this is to create a delegate protocol for the UniversitiesViewController.

@protocol UniversitiesViewControllerDelegate <NSObject>
- (void)universitiesViewController:(UniversitiesViewController *)uvc selectedIndex:(NSInteger)index;
@end

And add

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

to the UniversitiesViewController class.

In didSelectRow in the UniversitiesViewController, call

[self.delegate universitiesViewController:self selectedIndex:indexPath.row]

Then from MapsViewController, when instantiating UniversitiesViewController (or if using segues, in prepareForSegue) set the delegate to 'self'. And make MapsViewController handle the delegate method.

- (void)universitiesViewController:(UniversitiesViewController *)uvc selectedIndex:(NSInteger)index
{
     // do stuff
}

Upvotes: 2

Related Questions