Search code examples
iphonecore-datansmanagedobjectcontext

how do you create 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.


Solution

  • 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!