1

I am trying to use the .text of UITextField in my first view controller in another .text of UITextField in my second view controller, but my firstPage.firstTField.text turns out to be (null) in my second view controller even though I printed _firstTField.text in my first view controller and it printed out the input that was entered.

What may be the problem? Why is null?

FirstViewController.h

@property (weak, nonatomic) IBOutlet UITextField *firstTField;

SecondViewController.h

@property (weak, nonatomic) IBOutlet UITextField *secondTField;

SecondViewController.m

#import "FirstViewController.h"

- (void)viewDidLoad {
     [super viewDidLoad];
     FirstViewController *firstPage = [[FirstViewController alloc] init];
     _secondTField.text = firstPage.firstTField.text;
}
Community
  • 1
  • 1
Ko Ki
  • 43
  • 1
  • 5
  • Because the terribly-named `firstTField` is almost certainly not instantiated in the default `init` method of your `FirstViewController` class and probably relies on the view actually having been loaded. You instead need a reference to the actually previously instantiated view controller (or better yet, just have that view controller pass the string that you need to this one). – nhgrif Nov 12 '15 at 00:34
  • Possible duplicate of [All IBOutlets are nil](http://stackoverflow.com/questions/29865775/all-iboutlets-are-nil) – rkyr Nov 12 '15 at 00:37
  • Possible duplicate of [Passing Data between View Controllers](http://stackoverflow.com/questions/5210535/passing-data-between-view-controllers) – nhgrif Nov 12 '15 at 00:37

1 Answers1

0

You should treat a view controller's views as private. That's part of the appearance of the view controller, not it's function, and if objects outside of the view controller expect the views to look a certain way then when you change the appearance of the view controller's views it breaks other code. Bad.

In this situation it's worse. It just doesn't work, for the reason @nhgrif explains. You just created a new FirstViewController object, and it's views don't even exist yet. (A view controllers views are not created until the system is asked to display the view controller to the screen.)

You should create a property in your view controller that exposes the string(s) you need to read/write and use that instead.

However it's strange that you would create a new instance of a view controller and then immediately try to read text from one of it's fields. How can it possibly have useful data if the view controller was created on the line before? What are you expecting to happen?

Duncan C
  • 128,072
  • 22
  • 173
  • 272