How to transmit data between viewcontrollers [iOS] And viewcontrollerios
There are many ways to transmit data between viewcontrollers. The bloggers will summarize the two most commonly used methods for you:
We assume that there is View controller A and View controller B. In this case, View controller B is pushed by View controller A through the Navigation controller, that is to say, View Controller B is the subview controller of View Controller.
The following describes how to transmit data between view controllers through A-> B and B->.
1. View Controller A transmits data to View Controller B.
- Here, my view Controller A is ViewController View Controller B is CheckViewController. Connect View Controller A and View Controller B on the Storyboard, click link, 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;
- In the ViewController. m file, set-(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 data transmission of A-> B.
2. View Controller B transmits data to View Controller
Data cannot be transferred from the sub-View Controller to the parent View Controller Using the segue. The common practice is to use protocol as a listener. The specific method is as follows:
- Add the Protocol to CheckViewController. h (note that the added protocol is located between # import and # interface ):
@class LoadViewController;@protocol CheckViewDelegate <NSObject>-(void)LoadDataViewController:(CheckViewController *)controller didFinishLoadData:(NSMutableArray *)loadedArray;@end
- Add the attribute delegate as the listener in CheckViewController. h.
@property (nonatomic, weak) id <LoadViewDelegate> delegate;
- Call this method in CheckViewController. m.
[self.delegate LoadDataViewController:self didFinishLoadData:testArray];
- Add the protocol to the ViewController. h file.
- Add listener settings when the CheckViewController instance is pushed out
CheckVC.delegate = self;
- Implement the method in step 3 in the ViewController. m file.
-(void)LoadDataViewController:(CheckViewController *)controller didFinishLoadData:(NSMutableArray *)loadedArray{ self.currentArray = loadedArray;}
In this way, data transmission between B-> A is completed. Relatively complex.