I’ve been following the CS193p’s lectures on Core data and I’ve run into a problem when I’m inserting a new managed object.
The error is:
Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘+entityForName: could not
locate an entity named ‘Card’ in this model.’
I’ve created the “Card” entity in my data model file. However I have a feeling it isn’t finding the data model file correctly, since removing that file all together give the same error. I’m wondering how I can find out whether it is due the UIManagedDocument object not finding the data model that is causing this error.
Here is what I’m doing in my controller class:
NSURL *docURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *databaseURL = [docURL URLByAppendingPathComponent:@"Cards Database"];
self.cardsDatabase = [[UIManagedDocument alloc] initWithFileURL:databaseURL];
if (![[NSFileManager defaultManager] fileExistsAtPath:[self.cardsDatabase.fileURL path]]) {
[self.cardsDatabase saveToURL:self.cardsDatabase.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
NSLog(@"Done");
}];
} else if (self.cardsDatabase.documentState == UIDocumentStateClosed) {
NSLog(@"Closed");
[self.cardsDatabase openWithCompletionHandler:^(BOOL success) {
if (success) {
NSLog(@"Opened");
[self addSampleData];
}
}];
} else if (self.cardsDatabase.documentState == UIDocumentStateNormal) {
NSLog(@"Normal");
}
- (void)addSampleData
{
NSManagedObjectContext *context = self.cardsDatabase.managedObjectContext;
[context performBlockAndWait:^{
Card *card = [NSEntityDescription insertNewObjectForEntityForName:@"Card" inManagedObjectContext:context];
card.title = @"Test Title";
}];
[self.cardsDatabase saveToURL:self.cardsDatabase.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:^(BOOL success) {
NSLog(@"Saved");
}];
}
The error occurs on this line:
Card *card = [NSEntityDescription insertNewObjectForEntityForName:@"Card" inManagedObjectContext:context];
Try resetting the simulator(In device, remove the app), clean the build and run again. That should resolve most of the issues related to ‘could not locate entities’.