I made a very simple storyboard based project with two View Controllers.
I want to simply access a string declared in VC1 from VC2. The second VC should then display the text in a textfield upon the press of a button.
I do not want to use delegation, a separate class for global data or global variables and Extern. Instead, I read that it was easy to achieve variable sharing using a reference to one VC in the other.
For my code shown below, XCode didn't complain, however my problem is this: The NSLog in the second VC returns null.
If anybody can tell me how to amend the code to pass the string to the second VC/ tell me where I'm going wrong I would appreciate it.
VC1 Header:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property NSString* textToPassToOtherVC;
VC1 Implementation:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize textToPassToOtherVC = _textToPassToOtherVC;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_textToPassToOtherVC = @"Here is some text";
NSLog (@"Text in VC1 is: %@", _textToPassToOtherVC);
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
@end
VC2 Header:
#import <UIKit/UIKit.h>
@class ViewController;
@interface ViewController2 : UIViewController
@property (nonatomic, strong) ViewController *received;
@property (strong, nonatomic) IBOutlet UITextField *textDisplay;
- (IBAction)textButton:(id)sender;
@end
VC2 Implementation:
#import "ViewController2.h"
#import "ViewController.h"
@interface ViewController2 ()
@end
@implementation ViewController2
@synthesize textDisplay;
@synthesize received;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewDidUnload
{
[self setTextDisplay:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (IBAction)textButton:(id)sender {
NSLog (@"Text in VC1 from VC2 is: %@", self.received.textToPassToOtherVC);
textDisplay.text = self.received.textToPassToOtherVC;
}
@end