I have a simple app that i'm building to consolidate my little knowledge about core data. My main problem is that my method for get the NSManagedObjectContext returns nil. The way to get this is showed in one of the Stanford classes about core data. I'm doing something wrong, but i don't know what(My code looks identical with the one showed in class)... Of course, the results are a crash in my app, that complains about "+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name...", when i try to save the data, but my context is nil.
The code to get the NSManagedObjectContext:
- (void)setupFile {
NSURL *URL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentationDirectory
inDomains:NSUserDomainMask] lastObject];
URL = [URL URLByAppendingPathComponent:@"FlashCardCoreData"];
UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:URL];
if ([[NSFileManager defaultManager] fileExistsAtPath:[URL path]] == NO) {
[document saveToURL:URL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (success) {
self.sharedContext = document.managedObjectContext;
}
}];
} else if (document.documentState == UIDocumentStateClosed) {
// open the document
[document openWithCompletionHandler:^(BOOL success) {
if (success) {
self.sharedContext = document.managedObjectContext;
}
}];
} else {
self.sharedContext = document.managedObjectContext;
}
}
This class is a singleton class for share a global context that i can use in all of the controllers and forms for displaying/saving the objects...
Note: I didn't used the global context shared in the app delegate because i did't choose my app for use the core data(hence it's not an available property in the delegate), and i don't know how can i change that once my app is already created.
Can anyone help me? Any suggest will be appreciated.
Thanks for the attention.
The easiest way to see the correct way to implement CoreData is to simply create a new project and check the "Use Core Data" check box when setting up options for the project.
This will inject all of the boiler plate code that you need for initializing core data. You can then copy it into your singleton class.
You then need to make your Managed Object Data Model.
Once the Data Model is fully configured, simply create an NSManagedObject subclass for the Data Model. This will automatically pull all of the properties/relationships from the Data Model file.
Here is a great tutorial for setting up and implementing Core Data.