There are many ways to pass data between Viewcontroller, bloggers here summarize two of the most commonly used methods for everyone:
We assume that there is view controller A and view Controller B, where we set the view controller B to be by view controller A through navigation controller push, which means that view controller B is a child view controller of view Controller A.
Here we pass the data by A->b and B->a respectively to illustrate two ways to pass data between view controllers.
1. Pass data from view controller A to view controller B
- Here, my view controller A is Viewcontroller View Controller B is checkviewcontroller. On storyboard, connect view Controller A and view controller B, click Connect, and set Segueidentifier in the Property Settings window. Here we set it to Maintocheck.
- Define attribute _showarray in the CheckViewController.h file to receive data
@property (Strong, nonatomic) Nsarray *showarray;
- Set in VIEWCONTROLLER.M file-(void) Prepareforsegue: (Uistoryboardsegue *) Segue Sender: (ID) Sender method:
-(void) Prepareforsegue: (Uistoryboardsegue *) Segue Sender: (ID) sender{ if ([[Segue identifier] isequaltostring:@ " Maintocheck "]) { Checkviewcontroller *CHECKVC = [Segue Destinationviewcontroller]; Checkvc.showarray = [[Nsarray alloc] initwitharray:_currentarray];} }
This completes the A->B data transfer.
2. Pass data to view controller A by View Controller B
Passing data from a child view controller to a parent view controller cannot take advantage of segue. The usual practice is to use protocol as a listener. Here's how:
- Add the protocol in CheckViewController.h (note that the location added is between #import and #interface):
@class Loadviewcontroller; @protocol checkviewdelegate <nsobject>-(void) Loaddataviewcontroller: ( Checkviewcontroller *) Controller didfinishloaddata: (Nsmutablearray *) Loadedarray; @end
- Add the property delegate as a listener in CheckViewController.h.
@property (nonatomic, weak) ID <LoadViewDelegate> delegate;
- This method is called in CHECKVIEWCONTROLLER.M.
[Self.delegate loaddataviewcontroller:self Didfinishloaddata:testarray];
- Add the protocol in the ViewController.h file.
- To add a setup listener when you push out a Checkviewcontroller instance
Checkvc.delegate = self;
- Implement the method in the third step in the viewcontroller.m file.
-(void) Loaddataviewcontroller: (Checkviewcontroller *) controller didfinishloaddata: (Nsmutablearray *) loadedarray{ Self.currentarray = Loadedarray;}
This completes the B->a data transfer. Relatively complex.
Ways to pass data between Viewcontroller "IOS"