将 ManagedObjectContext 传递到视图/控制器层次结构
大多数情况下,托管对象上下文是在应用程序委托中创建的。 有哪些方法可以将其传递到视图/控制器层次结构,以便树中的每个导航/选项卡控制器都可以访问它。每次从父母到孩子传递它可能不是最好的,因为我必须每次都携带此信息,有时并非所有控制器都按照特定孩子的方式可能需要它。
Managed object context in most cases created in application delegate.
What are the ways of passing it along to view/controller hierarchy, so every navigation/tab controller in the tree can have access to it. Passing it every time from parent to child may not be the best since I have to carry this information every time and sometimes not all of the controllers to the way of particular child may need it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
推荐的设计是进行依赖注入。这意味着当您创建
UIViewController
时,您通过属性传入NSManagedObjectContext
。如果UIViewController
仅需要一个或一组NSManagedObject
实例,那么您只需通过属性传递它们即可。这种设计更加灵活,并且可以更好地重用代码。将所有内容链接到 AppDelegate 中的单个“硬编码”
NSManagedObjectContext
是脆弱的,并且会降低代码的灵活性。我在 Mac 开发者网络。 (编辑:现在通过 Wayback Machine 的缓存丢失了链接)
The recommended design is to do a dependency injection. This means that when you create a
UIViewController
you pass in theNSManagedObjectContext
via a property. If theUIViewController
only needs a single or set ofNSManagedObject
instances then you would just hand those in via properties.This design is more flexible and allows for greater reuse of your code. Linking everything to a single "hard-coded"
NSManagedObjectContext
in the AppDelegate is fragile and reduces the flexibility of your code.I discuss this in depth on The Mac Developer Network. (edit: lost link now via Wayback Machine's Cache)
您还可以在主 Nib 中创建主上下文对象。并将控制器与该对象链接起来。或者,如果您只使用一个 MOC,则创建一个单例。
You can also create a main context object in your main Nib. And link the controllers with this object. Or create a singleton if you only use one MOC.