Alex McPherson
Alex McPherson

Reputation: 3195

Update label in another View Controller from the appDelegate

I would like to update a label in one of my ViewControllers from the appDelegate. The Label in the view controller is all linked up in IB and has properties set.

In the AppDelegate .h

I am creating an ivar for the view controller so I can access the label on the view controller from the delegate like this.

someViewController *myView;

and in the AppDelegate.m file

myView.theLabel.text = @"Whatever";

I've also tried myView.theLabel setText: @"whatever";

Ive also tried making myView a property and synthesising it. I've tried the code in applicationDidFinishLaunching and applicationWillEnterForeground however the label never updates. Whats the best way to do this?

Upvotes: 4

Views: 2691

Answers (1)

Highrule
Highrule

Reputation: 1915

I would imagine that myView hasn't been created yet, so you have a null reference.

Try this to test that theory:

someViewController *myView;
if(myView)
    NSLog(@"Object has been created");
else
    NSLog(@"You have a null reference - The Object hasn't been created yet");

If this is the case, change the line to this to create it:

someViewController *myView = [[someViewController alloc] initWithNibName:@"SomeViewController" bundle:nil];
myView.theLabel.text = @"Something";
self.window.rootViewController = myView;

Yes, you create your first view in appDelegate, then set the rootViewController to that first view.

Upvotes: 3

Related Questions