Pass data back to previous viewcontroller
Solution 1:
You can use a delegate. So in your ViewController B you need to create a protocol that sends data back to your ViewController A. Your ViewController A would become a delegate of ViewController B.
If you are new to objective C, please look at What is Delegate.
Create protocol in ViewControllerB.h :
#import <UIKit/UIKit.h>
@protocol senddataProtocol <NSObject>
-(void)sendDataToA:(NSArray *)array; //I am thinking my data is NSArray, you can use another object for store your information.
@end
@interface ViewControllerB : UIViewController
@property(nonatomic,assign)id delegate;
ViewControllerB.m
@synthesize delegate;
-(void)viewWillDisappear:(BOOL)animated
{
[delegate sendDataToA:yourdata];
}
in your ViewControllerA : when you go to ViewControllerB
ViewControllerA *acontollerobject=[[ViewControllerA alloc] initWithNibName:@"ViewControllerA" bundle:nil];
acontollerobject.delegate=self; // protocol listener
[self.navigationController pushViewController:acontollerobject animated:YES];
and define your function:
-(void)sendDataToA:(NSArray *)array
{
// data will come here inside of ViewControllerA
}
Edited :
You can See this example : How you can Pass data back to previous viewcontroller: Tutorial link
Solution 2:
A shorter and simpler method than protocol/delegate is to create a closure:
For sending a String back in my case. In ViewControllerA:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let viewControllerB = segue.destination as? ViewControllerB {
viewControllerB.callback = { message in
//Do what you want in here!
}
}
}
In ViewControllerB:
var callback : ((String) -> Void)?
@IBAction func done(sender: AnyObject) {
callback?("Hi")
self.dismiss(animated: true, completion: nil)
}