Web Development

By the end of this post, you will be able to pass data between ViewControllers using objective-c.

ViewControllers

  • FirstController (where the data will come from)
  • SecondController (where the data will be sent to)

First of all, we would need to have some data in the FirstController. Let’s start by creating an NSString to the FirstController.m file:

@interface FirstController
- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *theData = @"I am awesome";
}
@end

Now in the SecondController.h file create a property:

@interface SecondController : UIViewController
@property (strong, nonatomic) NSString *theData;
@end

Lets import the SecondController to the FirstController by adding the following above the FirstController.m:

#import "SecondController.h"

Now, let’s pass the value to the SecondController, by modifying the FirstController.m

@interface FirstController
- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *theData = @"I am awesome";
    SecondController *secondController = [[SecondController alloc] init];
    secondController.theData = theData; // the value has been sent to the SecondController
}
@end

This is so easy. Try it yourself and experiment!