4

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?

Alladinian
  • 34,483
  • 6
  • 89
  • 91
Alex McPherson
  • 3,185
  • 3
  • 30
  • 41
  • Do you instantiate the controller in your app delegate, or by any other means get a reference to an instance of this controller? – Alladinian Jun 22 '12 at 19:58
  • @Alladinian in the .h as mentioned I create a ivar someViewController *myView and access the label this way. The someViewController.h header is added to appDelegate.h and appDelegate.m other than that not sure what you mean. Thanks for replying. – Alex McPherson Jun 25 '12 at 16:10
  • @Alladinian sorry me bing thick no I do not instantiate the view controller from the appdelegate should I be doing above the label I am accessing someViewController *myView = [[someViewController alloc]initWithNibName:@"someViewController" blah blah? – Alex McPherson Jun 25 '12 at 16:14
  • To set the label in your controller, you'll have to grab a reference of it _after_ you have alloc/init/present it. Where and how is your view controller added to the window? – Alladinian Jun 25 '12 at 16:16

1 Answers1

3

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.

Highrule
  • 1,915
  • 3
  • 19
  • 23