简体   繁体   中英

How to set properties on initial view controller (created in Storyboard) from AppDelegate?

I'm doing a call to an API in my AppDelegate.m didFinishLauncingWithOptions method. The JSON retrieved will be translated into an NSArray of objects. I'd like to set a property of my first view controller to that array so that view controller can use the latitude and longitude properties of those objects to map out locations.

Something like this:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // array retrieved - in actual application, this is an API call and translation
    Obj *object1 = [[Obj alloc] init];
    Obj *object2 = [[Obj alloc] init];
    Obj *object3 = [[Obj alloc] init];

    NSArray *arrayOfObjectsToMap = [NSArray arrayWithObjects:object1, object2, object3, nil];

    // pass object array along to first view controller
    firstController.objectList = arrayOfObjectsToMap;

    return YES;
}

I'm having trouble figuring out how to set properties on the first controller, which was created in Storyboard. The self.window.rootViewController of the AppDelegate is of type UIViewController and my initial controller is of type MapViewController with an NSArray property akin to the objectList property in the example above.

You can use the following method to pass the data to the view controller using the segue.

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"showDetailSegue"]){
        ViewControllerB *controller = (ViewControllerB *)segue.destinationViewController;
        controller.isSomethingEnabled = YES;
    }
}

Please follow the below post for more details. Passing Data between View Controllers

我决定通过将创建的对象保存到Core Data中来解决此问题(或者,我可以使用Singleton或其他存储方式),并创建我的初始视图控制器以从Core Data中读取对象。

Make sure that you import your view controller's header file:

#import "MapViewController.h"

Then, because you know that your initial view controller is of type MapViewController, just add a cast to the expression:

((MapViewController *)firstController).objectList = arrayOfObjectsToMap;

To make it more secure you can check if the view controller is really a MapViewController

if ([firstController isKindOfClass:[MapViewController class]]) {
    ((MapViewController *)firstController).objectList = arrayOfObjectsToMap;
}

Update

Another option would be a cast right where you assign your firstController variable:

MapViewController *firstController = (MapViewController *)self.window.rootViewController;

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