Pass data in modal segue in storyboard?

530 views Asked by At

My real problem is i want to pass data from childViewController to parentViewController in storyboard by modal segue.

Code

parentViewController.h

@property (strong, nonatomic)NSMutableArray *address;

childViewController.m

parentViewController *parent=(parentViewController *)self.presentingViewController;
post.address=@"Hello World";

This code throw exception like

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MainTabbarViewController setAddress:]: unrecognized selector sent to instance 0x7fa070e6b910'

storyboard structure

TabbarController-> NavigationController-> parentViewController-> childViewController

Thank you in Advance.

3

There are 3 answers

2
agy On BEST ANSWER

There is no way to get a reference to the segue that created you. You could create a property (sourceVC in my example) in the destination controller, and assign self to this property in the prepareForSegue method (in the source view controller):

[(ChildViewController *)segue.destinationViewController sourceVC] = self;

Anyway, I think it's a better solution to use a delegate.

* In ChildViewController.h *

@protocol ChildDelegate <NSObject>
- (void)postAddress:(NSString*)ad;
@end

@interface ChildViewController : UIViewController
@property (weak, nonatomic) id <ChildDelegate> delegate;
@end

* In ParentViewController.h *

@interface ParentViewController : UIViewController <ChildDelegate>
@end

* In ParentViewController.m *

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
       ChildViewController *vc = [segue destinationViewController];
       vc.delegate = self;
}

* In ChildViewController.m *

- (void)changeAddress:(NSString*)ad
{
   if ([self.delegate respondsToSelector:@selector(postAddress:)])
    {
        // Tell the delegate something.
        [self.delegate postAddress:@"New Address"];
    }
}
1
Vakas On

You cannot pass the data back to the parent view controller like this. Delegation is the best way to implement this. Please have a look on the following link where it is explained in detail.

passing-data-between-view-controllers

1
Mahmoud Adam On

the proper way to do that is using delegate

in ChildViewController.h

@protocol ChildDelegate 
- (void)postAddress:(NSString *)address;
@end 
@interface ChildViewController
@property (nonAtomic, assign) id<ChildDelegate> delegate;
@end

in ChildViewController.m

[self.delegate postAddress:address];

in ParentViewController.h

@interface ParentViewController <ChildDelegate>
@end

in ParentViewController.m

// presenting childViewController
- (void)presentChildViewController {   
    ChildViewController *childViewController = [[ChildViewController alloc]init];
    childViewController.delegate = self;
    [self presentViewController:childViewController animated:YES completion:nil];
}


// delegate method
- (void)postAddress:(NSString *)address{
    // add you code here
}