在macOS中初始化CoreData [英] Initializing CoreData in macOS

查看:47
本文介绍了在macOS中初始化CoreData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在可可中,情节提要的第一个视图控制器将在调用 AppDelegate applicationDidFinishLaunching 之前调用 viewDidLoad (在第一个视图控制器上).
由于我要在 applicationDidFinishLaunching 中抓取 NSManagedObjectContext ,因此需要先等待 applicationDidFinishLaunching 才能加载数据.

In Cocoa, Storyboard's first view controller will call viewDidLoad (on the first view controller) before AppDelegate's applicationDidFinishLaunching is called.
Since I am grabbing my NSManagedObjectContext in applicationDidFinishLaunching, I need to wait for applicationDidFinishLaunching before loading my data.

换句话说,在 viewDidLoad 中,我还没有 NSManagedObjectContext .

In other words, in viewDidLoad, I don't yet have my NSManagedObjectContext.

我现在正在做什么:

我要在 viewDidLoad 中添加一个 applicationDidFinishLaunching 观察器,并在触发该数据时加载数据.

I'm adding an applicationDidFinishLaunching observer in my viewDidLoad, and load the data when that is triggered.

所以(按顺序):
1. ViewController正在添加 applicationDidFinishLaunching 观察器.
2. AppDelegates运行其 applicationDidFinishLaunching 并触发观察者.
3.我可以从ViewController加载数据.

So (in order):
1. ViewController is adding an applicationDidFinishLaunching observer.
2. AppDelegates runs its applicationDidFinishLaunching and triggering the observer.
3. I can load the data from my ViewController.

我意识到我要在 viewDidLoad 上进行 laying ,在 applicationDidFinishLaunching 之前被调用.如果更改了该顺序,将在 applicationDidFinishLaunching 之后添加观察者,并且不会加载数据.

I realized I'm relaying on viewDidLoad to be called before applicationDidFinishLaunching. If that order is changed, the observer will be added after applicationDidFinishLaunching and data will not load.

让我的'CoreDataManager'直接在其 init 中从AppDelegate获取 NSManagedObjectContext 会更安全吗?

Would it be 'safer' to let my 'CoreDataManager' get the NSManagedObjectContext from AppDelegate directly in its init?

推荐答案

我可以建议改版设计,从AppDelegate类中删除对核心数据的任何使用,然后将所有初始化都移至您的根视图控制器中,然后使用依赖项注入将您的托管对象上下文传递给其他视图控制器(或将单独的核心数据管理器类实现为单例).这样可以将您从此类问题中解放出来.

May I suggest a revised design instead, remove any use of core data from the AppDelegate class and move any initialisation into your root view controller instead and then use dependency injection to pass your managed object context to other view controllers (or have a separate core data manager class implemented as a singleton). This will free you from issues like this.

这篇关于在macOS中初始化CoreData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆