user3556967
user3556967

Reputation: 1

Change UILabel from appDelegate

I want to do some stuff from the appDelegate in Xcode. One of these things are to change a UILabel.

ViewController *viewController = [[UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil]        instantiateViewControllerWithIdentifier:@"id"];


viewController.label.text = @"heeej";

I was told this would do the trick. Doesn't work. Label doesn't change. Does anyone know what the problem is?

Upvotes: 0

Views: 506

Answers (1)

dasdom
dasdom

Reputation: 14063

There are several problems:

  1. Don't do anything in the AppDelegate except for loading the window an the initial view controllers (if needed).
  2. You are instantiating a new view controller in the first line. I assume you already have a view controller and you want to change the label in that view controller. Than you need a reference to that view controller and use this reference to send messages to it.
  3. The label should not be a property of the view controller. You should try to follow the design pattern Model-View-Controller or the pattern Model-View-ViewModel. Ask you preferred search engine what those are if you don't know.
  4. id as an identifier for anything in Objective-C is a bad idea because this is used as an object type.

Edit: You don't need a reference to change a property in the view controller. Use notifications to update the label. The system sends a notification with the name UIApplicationWillEnterForgroundNotification' (see [here][1]). Add the view controller as an observer to the[NSNotificationCenter defaultCenter]` for this name and react on the notification. Read the Apple documentation if you don't know what I am talking about.

Upvotes: 1

Related Questions