简体   繁体   中英

Access View Controller's properties from AppDelegate

I currently have an Xcode project in which I am using Storyboards. In my AppDelegate, I need to set some properties that are contained in the .h files of other View Controllers in response to notifications that the app receives.

How do I instantiate a object of those view controllers in the AppDelegate so that I can access and modify their properties?

There are ways for the app delegate to get a handle to the right vc and communicate with it, but the better design is to have the information flow the other way around, letting the view controllers ask for information and update their own properties.

To do this, when the app delegate receives a notification, have it post a corresponding NSNotification (via NSNotificationCenter ). The view controllers who care about the change can add themselves as observers for this notification and get the information. How can they get it? A few ways:

The textbook way is to have a model on the application, probably a singleton that has properties relevant to the view controllers. Idea two is to effectively make your app delegate a model by giving it properties that the vcs can interrogate. Last idea, the userInfo param on postNotificationName:(NSString *)notificationName object:(id)notificationSender userInfo:(NSDictionary *)userInfo can convey information to the observer.

EDIT - NSNotificationCenter is pretty easy to use. It goes like this:

In AppDelegate.m, when you get an external notification:

// say you want a view controller to change a label text and its
// view's background color
NSDictionary *info = @{ @"text": @"hello", @"color": [UIColor redColor] };
[[NSNotificationCenter defaultCenter] postNotificationName:@"HiEverybody" object:self userInfo:info];

In SomeViewController.m, subscribe to the message:

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(observedHi:)
                                                 name:@"HiEverybody"
                                               object:nil];
}

// unsubscribe when we go away
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

// this method gets run when the notification is posted
// the notification's userInfo property contains the data that the app delegate provided
- (void)observedHi:(NSNotification *)notification {

    NSDictionary *userInfo = notification.userInfo;
    self.myLabel.text = userInfo[@"text"];
    self.view.backgroundColor = userInfo[@"color"];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM