Search code examples
objective-ccocoa-touchuiapplicationdelegate

Objective-C – Message a view controller from application delegate


I want to download some data in the application delegate in - application:didFinishLaunchingWithOptions:

After I have downloaded some data I want to set this data to an NSArray property in a view controller. If I have a synthesized property of NSArray (nonatomic, retain) called data I would like to do [viewController setData:downloadedData];

How would I call the active viewController instance from the application delegate?

My application structure is a Tab Bar Controller as root controller.


Solution

  • You'll want to use NSNotificationCenter which will essentially broadcast a message to all objects that have subscribed to that particular message.

    In your view controller subscribe to the notification:

    [[NSNotificationCenter defaultCenter] 
        addObserver:self 
        selector:@selector(downloadedData:) 
        notificationName:@"DownloadedData" 
        object:data];
    
    - downloadedData:(NSNotification *)notification {
        self.data = notification.object;
    }
    

    And in your app delegate send the notification to the subscribers:

    [[NSNotificationCenter defaultCenter] 
        postNotificationName:@"DownloadedData" 
        object:data];