简体   繁体   中英

How to share a model with multiple Controller?

I've got a first UISplitViewController in wich there is (and it's default) two other view Controller as children and for one of them there is another view controller as child (again it's default).

My problem is that the Model, which is basically a class, used by the business logic is created in the AppDelegate and i'd like to use it in every controller.

I tried to use the viewDidLoad method to pass the model through all the controller but this method is called in the last child and then go through the hierarchical tree to the SplitViewController.

Two constraints i'd like to fullfill are:

  • I don't want to use a singleton
  • I don't want all my controllers to know the AppDelegate

Is there a way to to this?

If you don't want to use singleton for any reason you have you can just pass model through those ViewControllers. Just create custom initWithModel: method for each of ViewControllers you have when you create them and hierarchically pass data to them. Maybe create a base class for all of them to keep it common.

For storyboard you can assign model in prepareForSeque method, just after creating ViewControllers.

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
     if([[segue identifier] isEqualToString:@"myViewController"])
     {
         [segue.destinationViewController setModel:self.model];
     }
}

That could be an answer :

in the .h :

+(MyModel *)shared;

in the .m :

static MyModel *myModel;

@implementation MyModel

+(MyModel *) shared{
    if (nil != myModel) {
        return myModel;
    }

    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        myModel = [[MyModel alloc] init];
    });
    return myModel;
}

In this way, you can access to your model anywhere of your app.

Hope that will help!

EDIT: add of dispatch_once

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