开发者

how do you create a NSManagedObjectContext

开发者 https://www.devze.com 2023-01-14 14:24 出处:网络
In core data for the iPhone, I was getting all sorts of errors trying to save data to a NSManagedObjectContext.

In core data for the iPhone, I was getting all sorts of errors trying to save data to a NSManagedObjectContext.

I believe that my issues were all to do with me using a NSManagedObjectContext that was being used in multiple threads.

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];
}

For more info, please have a look at Apple's Core Data Tutorial for iOS.

Cheers!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号