将 ManagedObjectContext 传递到视图/控制器层次结构

发布于 2024-09-08 07:19:28 字数 139 浏览 11 评论 0原文

大多数情况下,托管对象上下文是在应用程序委托中创建的。 有哪些方法可以将其传递到视图/控制器层次结构,以便树中的每个导航/选项卡控制器都可以访问它。每次从父母到孩子传递它可能不是最好的,因为我必须每次都携带此信息,有时并非所有控制器都按照特定孩子的方式可能需要它。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

薄情伤 2024-09-15 07:19:28

推荐的设计是进行依赖注入。这意味着当您创建 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 the NSManagedObjectContext via a property. If the UIViewController only needs a single or set of NSManagedObject 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)

宁愿没拥抱 2024-09-15 07:19:28

您还可以在主 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文