问题描述
在iPhone的核心数据中,我尝试将数据保存到 NSManagedObjectContext
时遇到各种错误。
In core data for the iPhone, I was getting all sorts of errors trying to save data to a NSManagedObjectContext
.
我相信我的问题都与我使用 NSManagedObjectContext
在多个线程中使用。
I believe that my issues were all to do with me using a NSManagedObjectContext
that was being used in multiple threads.
所以我想创建一个新的 NSManagedObjectContext
并尝试,但我找不到示例代码只是创建一个新的实例...
So I wanted to create a new NSManagedObjectContext
and try that, but I cannot find the example code to simply create a new instance...
我知道它的简单,但我真的很感谢任何帮助。
I know its simple, but I would really appreciate any help here.
注意,我看到这篇文章在苹果文档:
Note, I have seen this article on the Apple docs: http://developer.apple.com/iphone/library/documentation/cocoa/conceptual/CoreDataUtilityTutorial/Articles/05_createStack.html
但这使用了一些我不熟悉的代码,
But this uses some code that I am not familiar with, like the XMLStore which is not supported on the iPhone, etc.
推荐答案
这是创建新上下文的代码:
this is the code to create a new context:
- (NSManagedObjectContext *)managedObjectContext {
NSManagedObjectContext *managedObjectContext = nil;
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator:coordinator];
[managedObjectContext setUndoManager:nil];
}
return [managedObjectContext autorelease];
}
只需创建一个新的上下文实例,喜欢使用。
It's simply create a new instance of the context and set the store that you would like to use.
如果您有多家商店,那么您可以这样购买:
If you have multiple stores, you would go for something like that:
- (NSManagedObjectContext *)managedObjectContextForStore:(NSString *)store {
NSManagedObjectContext *managedObjectContext = nil;
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinatorForStore:store];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator:coordinator];
[managedObjectContext setUndoManager:nil];
}
return [managedObjectContext autorelease];
}
有关详情,请查看。
干杯!
这篇关于如何创建一个NSManagedObjectContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!