[英]How pass objects from AppDelegate to WindowController using Storyboards?
In my application delegate I create a NSManagedObjectContext
property that I want to pass to the window controller I launch in applicationDidFinishLaunching:
. 在我的应用程序委托中,我创建一个
NSManagedObjectContext
属性,该属性要传递给我在applicationDidFinishLaunching:
启动的窗口控制器。
This is basically my code in AppDelegate.m
: 这基本上是我在
AppDelegate.m
代码:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSStoryboard *storyboard = [NSStoryboard storyboardWithName:@"Main" bundle:nil];
self.setupWindowController = [storyboard instantiateControllerWithIdentifier:@"setup"];
self.setupWindowController.managedObjectContext = self.managedObjectContext;
[self.setupWindowController showWindow:self];
}
In MyWindowController.m
I have the following method: 在
MyWindowController.m
我具有以下方法:
- (void)setManagedObjectContext:(NSManagedObjectContext *)managedObjectContext {
((MyViewController *)self.contentViewController).managedObjectContext = managedObjectContext;
}
And this is a method from MyViewController.m
: 这是
MyViewController.m
的方法:
- (void)prepareForSegue:(NSStoryboardSegue *)segue sender:(id)sender {
if ([segue.destinationController isKindOfClass:self.class]) {
((MyViewController *)segue.destinationController).managedObjectContext = self.managedObjectContext;
}
}
This approach worked pretty well until I had to programmatically launch different windows from the application delegate. 在我不得不以编程方式从应用程序委托启动不同的窗口之前,这种方法非常有效。 The problem now is that
prepareForSegue:sender:
for the initial view is called before I'm able to set the MyWindowController.managedObjectContext
, so it'll only pass nil
with the following segues. 现在的问题是,在我能够设置
MyWindowController.managedObjectContext
之前,要为初始视图调用prepareForSegue:sender:
:,因此它只会在以下segues中传递nil
。
How on earth should I pass objects from my app delegate to the initial window controller before it sets up the view hierarchy? 在建立视图层次结构之前,应如何将对象从应用程序委托传递给初始窗口控制器?
Am I approaching all this the wrong way? 我是否以错误的方式处理所有这一切?
I suggest reducing the dependencies among controllers by making a data model layer in your application. 我建议通过在应用程序中创建数据模型层来减少控制器之间的依赖性。
The data model would manage the information that the controllers use and provide an application-specific facade in front of CoreData. 数据模型将管理控制器使用的信息,并在CoreData前面提供特定于应用程序的外观。 The data model object(s) can be shared instances or can be requested from a known object, such as the app delegate.
数据模型对象可以是共享实例,也可以从已知对象(例如应用程序委托)中请求。
That way, the model is only referenced where needed and doesn't clutter interfaces just as a pass-through object. 这样,仅在需要的地方引用模型,而不会像传递对象那样使接口混乱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.