如何阻止 Core Data 应用程序自动加载 ManagedObjectContext?
我正在构建一个核心数据应用程序,该应用程序在启动时检查保存的用户登录信息,然后设置模型、存储、协调器和上下文。我遇到的唯一问题是,一旦用户单击界面中的任何视图,应用程序就会尝试获取 ManagedObjectContext ,从而导致异常,因为我尚未创建存储。
有什么办法可以阻止它这样做吗?
干杯。
I am building a core data application that checks for a saved user login upon launch and sets up the model, store, coordinator and context afterwards. The only problem I have is that as soon as the user clicks on any view in the interface, the application tries to get the managedObjectContext causing an exception seeing as I haven't created the stores yet.
Is there any way to stop it from doing this?
Cheers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用 Apple 提供的 Coredata 样板内容,您会注意到,当访问 ManagedObjectContext 对象的属性时,会延迟加载该对象。
只需告诉视图控制器通过其属性(即 self.managementObjectContext)访问上下文,而不是直接访问变量,上下文、对象模型和持久存储协调器将被适当地创建。
PS:这只是一个猜测,因为您没有在这里发布任何相关代码。
If you're using the Coredata boiler plate stuff provided by Apple, you will notice the managedObjectContext object is loaded lazily when its property is accessed.
Simply tell your view controller to access the context via its property (i.e. self.managedObjectContext) instead of accessing the variable directly, and the context, object model and persistent store coordinator will be created appropriately.
PS: This is just a guess as you didn't post any of your related code here.
为什么要显示依赖于托管对象上下文的视图,而没有创建它或安排在访问时创建它?
通常的模式是让托管对象上下文 getter 看起来像这样:(
在此代码中,
_managementObjectContext
是类中用于保存上下文的 ivar)。这样,上下文就会在需要时自动创建。 Apple 的标准示例代码就可以为您做到这一点。Why are you showing views that depend on the managed object context without either creating it already or arranging for it to be created on access?
The usual pattern is to have your managed object context getter look something like this:
(in this code,
_managedObjectContext
is an ivar in the class to hold the context). That way the context gets created automagically when needed. Apple's standard sample code does just this for you.