iosdata-objects

iOS/objective-c: Pass object to new view controller


I am launching a modal view controller in code and wish to pass along a data object. I have created a property on the destination VC for the object. The new VC is launching fine but not getting the data object. Is there anything wrong with the following code? If not, I will have to look for error somewhere else but wondering if this is right way to pass data object.

//in header file of destination VC
@property (nonatomic, strong) Product *product;

//in .m file of starting VC
- (void) gotoStoryboard {
    UIStoryboard *storyBoard = self.storyboard;
    moreInfoVC *infoVC =
    [storyBoard instantiateViewControllerWithIdentifier:@"moreInfo"];
      infoVC.product = _product;//IS THIS ADEQUATE TO PASS DATA OBJECT?
     UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController: infoVC];
    [self presentModalViewController:nav animated:YES];
}

Solution

  • You should use the prepareForSegue Storyboard delegate.

    First you call the view to move to the next view via a segue identifier like this:

    [self performSegueWithIdentifier:@"YourSegueIdentifier" sender:self];
    

    Then you add this code in the same .m file as the code above. This prepares the next view with the data or items you want it to have.

    -(void)prepareForSegue:(UIStoryboard *)segue sender:(id)sender {
        if ([segue.identifier isEqualToString:@"YourSegueIdentifier"]) {
            MoreInfoViewController * moreInfoVC = segue.destinationViewController;
            // This is how you will pass the object or data you want for the next view
            moreInfoVC.aStringToPass = @"I am passing this string";
            moreInfoVc.myCustomObjectToPass = theCustomObject;
        }
    }
    

    Then you must have the object as a property in the .h file of the view that you are going to with the segue.

    // MoreInfoViewController.h
    @property NSString * aStringToPass;
    @property CustomObject * myCustomObjectToPass;