xcode 有没有办法获得 NSManagedObjectContext 而不必每次都调用我的 AppDelegate?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4910529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to get NSManagedObjectContext without having to calling my AppDelegate every time?
提问by Ethan Allen
I created an app from a Xcode template and selected "Core Data" as an option, so all of the Core Data delegates and main methods would be included in the AppDelegate files.
我从 Xcode 模板创建了一个应用程序,并选择了“Core Data”作为选项,因此所有 Core Data 委托和主要方法都将包含在 AppDelegate 文件中。
Now, every time I have to get the context in order to use Core Data, I'm using the following code:
现在,每次我必须获取上下文才能使用 Core Data 时,我都使用以下代码:
MovieCatalogAppDelegate *appDelegate = (MovieCatalogAppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
Is there anyway to get the managedObjectContext without needing to call directly to the MovieCatalogAppDelegate? I want to make it a generic call so my data files aren't necessarily bound to MovieCatalogAppDelegate.h. Basically, I am trying to decouple the code and make things more dynamic without need to know direct names.
有没有办法在不需要直接调用 MovieCatalogAppDelegate 的情况下获取 managedObjectContext?我想让它成为一个通用调用,所以我的数据文件不一定绑定到 MovieCatalogAppDelegate.h。基本上,我试图解耦代码并使事情更加动态,而无需知道直接名称。
Thanks.
谢谢。
回答by Jablair
There are a few different options.
有几种不同的选择。
You could move your Core Data support code into a class other than your app delegate. Make it a singleton, if you'd like.
You could pass in your managed object context as a property of each view controller.
If you have an
NSManagedObject
that you're already passing around, you can get theNSManagedObjectContext
from themanagedObjectContext
of said object.
您可以将 Core Data 支持代码移动到应用程序委托以外的类中。如果您愿意,可以将其设为单身。
您可以将托管对象上下文作为每个视图控制器的属性传入。
如果您有一个
NSManagedObject
已经在传递的 ,则可以NSManagedObjectContext
从managedObjectContext
所述对象的 中获取 。
There are some ideas in this articleon CIMGF.
回答by Zebs
The official answer (Apple Documentation) is that you should have a pointer to the managedObjectContext on every single one of the classes that will use it and pass it along any other objects that need to use it.
官方答案(Apple 文档)是,您应该在每个将使用它的类上都有一个指向 managedObjectContext 的指针,并将它传递给需要使用它的任何其他对象。
You can set it as a property of your UIViewControllers (or any other object) and set it upon creation; so on your code you will just need to call:
您可以将其设置为 UIViewControllers(或任何其他对象)的属性并在创建时进行设置;所以在你的代码中,你只需要调用:
self.managedObjectContext
self.managedObjectContext
Instead of going all the way to the delegate.
而不是一路走到代表处。
If you need more info just comment and I will update the answer.
如果您需要更多信息,请发表评论,我会更新答案。