[英]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). 我有一个第一个UISplitViewController,其中(默认是)另外两个View Controller作为子级,对于其中一个,还有另一个View Controller作为子级(同样是默认值)。
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. 我的问题是,业务逻辑使用的模型(基本上是一个类)是在AppDelegate中创建的,我想在每个控制器中使用它。
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. 我尝试使用viewDidLoad方法将模型传递给所有控制器,但该方法在最后一个子级中调用,然后通过层次结构树到达SplitViewController。
Two constraints i'd like to fullfill are: 我想满足的两个约束是:
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. 如果由于任何原因不想使用单例,则可以通过这些ViewController传递模型。 Just create custom initWithModel: method for each of ViewControllers you have when you create them and hierarchically pass data to them.
只需为创建的每个ViewController创建自定义initWithModel:方法,然后将数据分层传递给它们。 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. 对于情节提要,您可以在创建ViewControllers之后立即在prepareForSeque方法中分配模型。
-(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
: 在
.h
:
+(MyModel *)shared;
in the .m
: 在
.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
编辑:添加
dispatch_once
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.