MVC 友好的核心数据方法
好吧,我对核心数据还很陌生,我现在开始深入研究它,我对实现它的正确方法有疑问。
我有一个从 appDelegate 加载的parentViewController 对象。 ParentView 是一个为另外三个 viewController 对象(它的子对象)设置分页 UIScrollView 的视图。视图加载完毕,我可以在三个视图之间完美地进行翻页。
所有三个视图都需要与核心数据进行大量数据交换。我是否应该将 ManagedObjectContext 的引用传递到 ParentView 中的每个不同视图中,以便所有视图都可以从 Core Data 中提取或写入 Core Data 本身?或者我应该将引用保留在parentView中,并让子级将请求传递给父级来处理?
谢谢
Ok so I am pretty new to Core Data, and I am now starting to dig into it more and I have a question about the correct way to implement it.
I have a parentViewController object that is loaded from the appDelegate. The parentView is a view that sets up a paging UIScrollView for three more viewController objects, it's children. The view loads up and I can page between the three views beautifully.
All three of the views need to have a significant amount of data exchange with Core Data. Should I pass the reference of the managedObjectContext into each different view within the parentView so that all the views can pull from and write to Core Data themselves? Or should I keep the reference in the parentView, and let the children pass the requests to the parent to handle?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我通常使用第三个选项,至少对于具有在应用程序的整个生命周期中访问的单个持久性存储的简单应用程序:将 ManagedObjectContext 设置为应用程序委托的属性,并在应用程序启动时对其进行初始化。然后,您可以使用以下方法从应用程序中的任何位置访问它:
这种方法并不适合所有设计和架构,但我发现它对我来说效果很好,并使我的代码相对干净。
I have typically used a third option, at least for simple applications with a single persistence store that I access throughout the lifetime of the app: Make the managedObjectContext a property of your application delegate, and initialize it when the application is started. Then, you can access it from anywhere in your application using something like:
This approach is not ideal for all designs and architectures, but I'm finding it works well for me and keeps my code relatively clean.
在 MVC 中,控制器不应直接相互通信。任何需要在控制器之间共享的数据都应该通过模型层共享,MOC 是模型层的一部分。因此,理想情况下,您应该将 MOC 传递给每个需要使用它的对象。完全可以让多个对象同时读/写同一个 MOC;尊重依赖注入的原则;并且可能需要编写更少的代码。
Controllers should never communicate directly with each other in MVC. Any data that needs to be shared between controllers should be shared through the model layer, of which the MOC is a part. So, ideally, you should pass the MOC to every object that needs to use it. Perfectly OK to have multiple objects reading/writing to the same MOC simultaneously; respects principles of Dependency Injection; and probably less code to write.