I know this question have been asked alot by other developers also.
I am using CORE DATA.
On last run of the code it was working fine but today when I build and Run the application i found this error.
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Cannot create an NSPersistentStoreCoordinator with a nil model'
may be some error came to my code mistakenly...
Here is the code have a look...
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}
- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"CrudWithInterface" withExtension:#"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"CrudWithInterface.sqlite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
Put a breakpoint inside your managedObjectModel getter. That exception indicates that _managedObjectModel will most likely be nil. I suspect that modelURL will also be nil.
If both of those things are true, check to make sure your Core Data model is still a part of the Target you are building.
Related
I have been trying like hell to figure out how to establish a connection between my Core Data & my SQL database. The database isn't pre-populated, but it will be used amongst many different users when it's launched.
I have gone through the Core Data & iCloud classes provided by Stanford three times to no avail. I have also looked throughly into SQLite/SQL relational databases in iOS to no avail. The only other option I have is to come on here, post all the code I can, and pray that somebody will have an answer for me. So here it goes...
AppDelegate.m
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
#pragma mark - Core Data stack
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}
- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [self applicationDocumentsDirectory];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"shindy.sqlite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
#pragma mark - Application's Documents directory
- (NSURL *)applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"shindy.sqlite"];
return [NSURL fileURLWithPath:path];
}
HomeViewController.m
- (void)setupFetchedResultsController
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Shindy"];
request.sortDescriptors = [NSArray arrayWithObjects:
[NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES],
[NSSortDescriptor sortDescriptorWithKey:#"dateAndTime" ascending:YES],
[NSSortDescriptor sortDescriptorWithKey:#"photo" ascending:YES],
[NSSortDescriptor sortDescriptorWithKey:#"details" ascending:YES],
[NSSortDescriptor sortDescriptorWithKey:#"timePosted" ascending:YES],
[NSSortDescriptor sortDescriptorWithKey:#"location" ascending:YES],
nil];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.shindyDatabase.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
}
- (void)fetchShindyDataIntoDocument:(UIManagedDocument *)document
{
dispatch_queue_t fetchQ = dispatch_queue_create("Shindy Fetcher", nil);
dispatch_async(fetchQ, ^{
NSArray *shindys = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSLog(#"shindys = %#", shindys);
[document.managedObjectContext performBlock:^{
for (NSDictionary *shindyInfo in shindys) {
[Shindy shindyWithShindyDBInfo:shindyInfo inManagedObjectContext:document.managedObjectContext];
NSLog(#"fire");
}
}];
});
}
- (void)useDocument
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"shindy.sqlite"];
if (![[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil]) {
[self.shindyDatabase saveToURL:self.shindyDatabase.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
[self setupFetchedResultsController];
[self fetchShindyDataIntoDocument:self.shindyDatabase];
}];
} else if (self.shindyDatabase.documentState == UIDocumentStateClosed) {
[self.shindyDatabase openWithCompletionHandler:^(BOOL success) {
[self setupFetchedResultsController];
}];
} else if (self.shindyDatabase.documentState == UIDocumentStateNormal) {
[self setupFetchedResultsController];
}
}
- (void)setShindyDatabase:(UIManagedDocument *)shindyDatabase
{
[self useDocument];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self fetchShindyDataIntoDocument:self.shindyDatabase];
if (!self.shindyDatabase) {
[self setShindyDatabase:self.shindyDatabase];
}
}
Shindy+ShindyDB.m
+ (Shindy *)shindyWithShindyDBInfo:(NSDictionary *)shindyInfo
inManagedObjectContext:(NSManagedObjectContext *)context
{
Shindy *shindy = nil;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Shindy"];
NSSortDescriptor *dateAndTimeSort = [NSSortDescriptor sortDescriptorWithKey:#"dateAndTime" ascending:YES];
NSSortDescriptor *detailsSort = [NSSortDescriptor sortDescriptorWithKey:#"details" ascending:YES];
NSSortDescriptor *locationSort = [NSSortDescriptor sortDescriptorWithKey:#"location" ascending:YES];
NSSortDescriptor *nameSort = [NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES];
NSSortDescriptor *photoSort = [NSSortDescriptor sortDescriptorWithKey:#"photo" ascending:YES];
NSSortDescriptor *timePostedSort = [NSSortDescriptor sortDescriptorWithKey:#"timePosted" ascending:YES];
// title
request.sortDescriptors = [NSArray arrayWithObjects:dateAndTimeSort, detailsSort, locationSort, nameSort, photoSort, timePostedSort, nil];
NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];
if (!matches || ([matches count] > 1)) {
// handle error
} else if ([matches count] == 0) {
shindy = [NSEntityDescription insertNewObjectForEntityForName:#"Shindy" inManagedObjectContext:context];
shindy.dateAndTime = [shindyInfo objectForKey:#"dateAndTime"];
shindy.details = [shindyInfo objectForKey:#"details"];
shindy.location = [shindyInfo objectForKey:#"location"];
shindy.name = [shindyInfo objectForKey:#"name"];
shindy.photo = [shindyInfo objectForKey:#"photo"];
shindy.timePosted = [shindyInfo objectForKey:#"timePosted"];
// title
// Guestlist? The rest?
// Use below for reference
shindy.whoseShindy = [User userWithName:[shindyInfo objectForKey:#"whoseShindy"] inManagedObjectContext:context];
} else {
shindy = [matches lastObject];
}
shindy = [NSEntityDescription insertNewObjectForEntityForName:#"Shindy" inManagedObjectContext:context];
shindy.dateAndTime = [shindyInfo objectForKey:#"dateAndTime"];
shindy.details = [shindyInfo objectForKey:#"details"];
shindy.location = [shindyInfo objectForKey:#"location"];
shindy.name = [shindyInfo objectForKey:#"name"];
shindy.photo = [shindyInfo objectForKey:#"photo"];
shindy.timePosted = [shindyInfo objectForKey:#"timePosted"];
return shindy;
}
AddShindyViewController.m
- (void)saveShindyToDatabase
{
NSArray *shindys = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
[self.shindyDatabase.managedObjectContext performBlock:^{
for (NSDictionary *shindyInfo in shindys) {
[Shindy shindyWithShindyDBInfo:shindyInfo inManagedObjectContext:self.shindyDatabase.managedObjectContext];
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
// url = [url URLByAppendingPathComponent:#"Default Shindy Database"];
self.shindyDatabase = [[UIManagedDocument alloc] initWithFileURL:url];
[self.shindyDatabase setValue:self.detailView.text forKey:#"details"];
if (FBSession.activeSession.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
self.name = user.name;
self.photo.profileID = user.id;
self.username = user.username;
}
}];
}
[self.shindyDatabase setValue:self.name forKey:#"name"];
[self.shindyDatabase setValue:self.photo forKey:#"photo"];
[self.shindyDatabase setValue:self.username forKey:#"username"];
// [Guest guestWithName:self.name username:self.username photo:self.photo inManagedObjectContext:self.shindyDatabase.managedObjectContext];
[self.shindyDatabase setValue:self.locationManager.location forKey:#"location"];
[self.shindyDatabase setValue:self.dateAndTimePicker.date forKey:#"dateAndTime"];
}
}];
}
I know what I'm asking for is a hell of a lot, but I have exhausted every single resource I have at my disposal. If anybody can even just point me in the right direction, I would be eternally grateful!
If you plan to map an existing database with CoreData you will be unsuccessful.
There's infact no way you can map any database with CoreData.
Core Data infact is a graph object management, with different storage option, and sqllite is just one of the possibility. At startup, if you choose sqllite as option, your application is going to create a database with a specific tables structure. If you try to connect to a database not created by CoreData framework you will get an error.
What you can do is get rid of CoreData, and build your NSObject to act like entities. But then, you will have to implement all the logic to save, update, versioning, concurrency ecc... and it's a long (and buggy) way, especially in a multi user environment.
Otherwise, tell me if I misunderstood your question. Maybe, you can post an error stack trace.
I'm getting this error while trying to use Core Data:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An instance of NSFetchedResultsController requires a non-nil fetchRequest and managedObjectContext'
I traced the error back to this in my modal view controller which contains the Table View:
- (void)setupFetchedResultsController
{
NSString *entityName = #"Location";
NSLog(#"Setting up a Fetched Results Controller for the Entity named %#", entityName);
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
// ERROR OCCURS IN THE LINE BELOW vvv
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
[self performFetch];
}
This is what I have in my AppDelegate:
- (void)setupFetchedResultsController
{
NSString *entityName = #"Location";
NSLog(#"Setting up a Fetched Results Controller for the Entity named %#", entityName);
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
[self.fetchedResultsController performFetch:nil];
}
I get no errors there, and here's more of the App Delegate:
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil)
{
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
{
// Using abort() right now just for development
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
#pragma mark - Core Data stack
- (NSManagedObjectContext *)managedObjectContext
{
if (__managedObjectContext != nil)
{
return __managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
__managedObjectContext = [[NSManagedObjectContext alloc] init];
[__managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return __managedObjectContext;
}
- (NSManagedObjectModel *)managedObjectModel
{
if (__managedObjectModel != nil)
{
return __managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"Model" withExtension:#"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return __managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil)
{
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"Forecaster.sqlite"];
NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __persistentStoreCoordinator;
}
#pragma mark - Application's Documents directory
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
and in my Model.xcdatamodeid:
Any help would be great! Thanks!
Here is the Method:
- (void)setupFetchedResultsController
{
NSManagedObjectContext *moc = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:#"Location" inManagedObjectContext:moc];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSError *error = nil;
NSArray *array = [moc executeFetchRequest:request error:&error];
if (array == nil)
{
// Deal with error...
}
else
{
// your data is in array
}
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"FailedBankInfo"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (FailedBankInfo *info in fetchedObjects) {
NSLog(#"Name: %#", info.name);
FailedBankDetails *details = info.details;
NSLog(#"Zip: %#", details.zip);
}
this is my delegate.m
#import "TestSaveDataAppDelegate.h"
#import "TestSaveDataViewController.h"
#implementation TestSaveDataAppDelegate
#synthesize window = _window;
#synthesize viewController = _viewController;
#synthesize managedObjectContext = __managedObjectContext;
#synthesize managedObjectModel = __managedObjectModel;
#synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
This is my NSManagedObjectContext
- (NSManagedObjectContext *)managedObjectContext
{
if (__managedObjectContext != nil) {
return __managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
__managedObjectContext = [[NSManagedObjectContext alloc] init];
[__managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return __managedObjectContext;
}
This is my NSManagedObjectModel
- (NSManagedObjectModel *)managedObjectModel
{
if (__managedObjectModel != nil) {
return __managedObjectModel;
}
__managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
return __managedObjectModel;
}
This is my NSPersistentStoreCoordinator
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil) {
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"SaveData.sqlite"];
NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __persistentStoreCoordinator;
}
In my TestSaveDataViewController.h i import my Savedata.h exactly name like inside my Model.xcdatamodeld with entity name is Savedata, attribute inside here is saveslot1 with string type.
in my TestSaveDataViewController.m
#synthesize managedObjectContext;
i have a button like this
- (IBAction)button1:(id)sender
{
// save text in textfield
Savedata *savedata = (Savedata *)[NSEntityDescription insertNewObjectForEntityForName:#"Savedata" inManagedObjectContext:managedObjectContext];
[savedata setSaveslot1:label1.text];
NSError *error;
if (![managedObjectContext save:&error]) {
// This is a serious error saying the record could not be saved.
// Advise the user to restart the application
}
}
When the button is push, the text in the textfield will save and show it label1.text
but i got this error.
+entityForName: could not locate an NSManagedObjectModel for entity name 'Savedata''
how to fix it?
i already solve my problem. i forgot to delegate it. now it works.
V. iOS 5
I have my Model2.xcdatamodelId containg 2 Entities. My Model is named 2, because I already have a Singleton named Model for some managing.
So from that, I have Model2.h and Model2.m.
My Problem : The first time, my Model2 is initialise, I put in some default data, then I commit. Works good, it says that my Model2 has been saved correctly. After what I am reading my data, data are shown from the database.. so it is successfuly in the database. BUT.. when closing and killing my app, my app seems to have lost all data.. and start over again with creating default data cause it is empty...
TIP: I'm thinking my problem could be about the initialize.. whithin those lines:
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSURL * storeUrl = [NSURL fileURLWithPath: [basePath stringByAppendingPathComponent: #"ProjectXYZ.db"]];
Since ProjectXYZ.db doesn't exist, it should create it?.. that's the part where I'm getting lost.. but it seems to worked on another project I've worked on... :S
Here's my Model2.h
#import <CoreData/CoreData.h>
#import "Photos_Trophies.h"
#import "Trophies.h"
#interface Model2 : NSObject
// High-level methods.
+ (void) commit;
...
// Object Retrieval
+ (NSArray*) trophies;
...
// Object Creation
+ (id) trophiesWithTitle:(NSString *)title;
#end
And my Model2.m
#import "Model2.h"
#import <UIKit/UIKit.h>
static NSManagedObjectContext * ctx;
#implementation Model2
+ (void) initialize {
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSURL * storeUrl = [NSURL fileURLWithPath: [basePath stringByAppendingPathComponent: #"ProjectXYZ.db"]];
NSError * error = nil;
ctx = [[NSManagedObjectContext alloc] init];
ctx.persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[NSManagedObjectModel mergedModelFromBundles:nil]];
ctx.undoManager = [[NSUndoManager alloc] init];
if (![ctx.persistentStoreCoordinator addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
NSLog(#"%#", error);
}
//TEMPORARY... these are default trophies for example
if ([[Model2 trophies] count] == 0) {
[self trophiesWithTitle:#"Saved Trophy Test 1"];
[self trophiesWithTitle:#"Saved Trophy Test 2"];
[self trophiesWithTitle:#"Saved Trophy Test 3"];
[self commit];
}
}
+ (void) commit {
NSError* error = nil;
if (![ctx save:&error]) {
NSLog(#"ERREUR DANS COMMIT: %#", error.localizedDescription);
NSArray* detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey];
if(detailedErrors && [detailedErrors count] > 0) {
for(NSError* detailedError in detailedErrors)
NSLog(#"DetailedError: %#", [detailedError userInfo]);
} else
NSLog(#"%#", [error userInfo]);
} else
NSLog(#"Model2 SAVED");
}
+ (NSArray*) trophies {
NSFetchRequest* req = [[NSFetchRequest alloc] init];
req.entity = [NSEntityDescription entityForName:#"Trophies" inManagedObjectContext:ctx];
req.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"trophies_title" ascending:YES]];
NSError* error = nil;
NSArray* objects = [ctx executeFetchRequest:req error:&error];
return objects;
}
+ (id) trophiesWithTitle:(NSString *)title {
Trophies * trophies = [NSEntityDescription insertNewObjectForEntityForName:#"Trophies" inManagedObjectContext:ctx];
trophies.trophies_title = title;
return trophies;
}
Your problem is this: NSInMemoryStoreType You need to use a persistent backing store.
Do something like this:
NSURL *storeUrl = [NSURL fileURLWithPath:[self persistentStorePath]];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeUrl
options:options
error:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
Typical reasons for an error here include:
* The persistent store is not accessible
* The schema for the persistent store is incompatible with current managed object model
Check the error message to determine what the actual problem was.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
NSAssert(error == nil, #"error creating persistentStoreCoordinator");
}
I need to use core data to persist data for my project, what I have done so far compiles well, but when I actually start storing things using core data, the program just quits, and I don't know the reason. I set up all the required components for core data in the appDelegate file, and I want to store data in a viewController called DetailViewController. Here is what I have done:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// Set the tab bar controller as the window's root view controller and display.
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
//this is what I added, reference managedObjectContext in the detail view controller.
detailViewController = [[DetailViewController alloc] init];
detailViewController.managedObjectContext = [self managedObjectContext];
return YES;
}
All components for core data have been implemented
- (NSManagedObjectContext *) managedObjectContext {
if (managedObjectContext != nil) {
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
}
return managedObjectContext;
}
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel != nil) {
return managedObjectModel;
}
managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];
return managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]
stringByAppendingPathComponent: #"MyProjectName.sqlite"]];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:[self managedObjectModel]];
if(![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil URL:storeUrl options:nil error:&error]) {
/*Error for store creation should be handled in here*/
}
return persistentStoreCoordinator;
}
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
When I try to call a method in the detail view to store data, the program quits.
-(IBAction) addItem {
Info *info = [NSEntityDescription insertNewObjectForEntityForName:#"Info"
inManagedObjectContext:managedObjectContext];
info.name = item.name;
}
item is the current object in the detail view, Info is the model class file. Do I miss something here?
Thanks!
Update:
The error message in the console is:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'Info''
But I do have a Info.xcdatamodel file in the "Resources" folder, and entity name is "Info".
Did you call [self.managedObjectContext save:&error]?
Also, perhaps your bundle loading routine does not work correctly. Try loading the managedObjectContext like this:
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"ModelName"
withExtension:#"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc]
initWithContentsOfURL:modelURL];
return __managedObjectModel;
My guess would be that in your detail view controller you either aren't synthesizing managedObjectContext or you aren't initializing it when creating your detail view controller. Check that both of those are being done. If that doesn't solve the problem, please check the console output after the crash and post any relevant information there in an update to your question.