adr
adr

Reputation: 205

How to change the text of a textField from another view

I have this code:

ViewController .h

@property IBOutlet UITextField *field;

ViewController .m

@synthesize field;

ViewControllerTwo .h

#import "ViewController.h" 
{
ViewController *ViewCont;
}
-(IBAction)changeTextField

ViewControllerTwo .m

#import "ViewController.h"

-(IBAction)changeTextField{
   viewCont.field.text = @"hello";
}

The problem is that it doesn't work, although it doesn't give me any error. Does anyone know what I'm doing wrong?

Upvotes: 0

Views: 117

Answers (2)

Rob Napier
Rob Napier

Reputation: 299643

Never modify another view controller's views. You are encountering one of many problems doing that. In your case, the likely cause is that the other view controller has not yet loaded its view, so all the IBOutlets are still nil.

You're breaking MVC, and that's going to cause lots of little problems like this. Instead of having ViewControllerTwo modify the outlets of ViewController, you should move the data (@"hello") into a model object that is shared by both view controllers. ViewControllerTwo would write to it, and ViewController would read from it. You can share that model object by passing it to the view controllers as a property, or by making the model a singleton.

Upvotes: 1

CodaFi
CodaFi

Reputation: 43330

You aren't instantiating your instance of class ViewController, so you are essentially sending a message to nil.

Upvotes: 0

Related Questions