Core Data unresolved error on save - iphone

I'm getting an error when saving my core data context, here is the log:
Unresolved error Error Domain=NSCocoaErrorDomain Code=134030 "The operation couldn’t be completed. (Cocoa error 134030.)" UserInfo=0x1937a0 {NSAffectedStoresErrorKey=(
"<NSSQLCore: 0x156410>"
), NSUnderlyingError=0x181a60 "The operation couldn’t be completed. (Cocoa error 4.)", NSFilePath=/var/mobile/Applications/appid/Documents/appname.sqlite}, {
NSAffectedStoresErrorKey = (
"<NSSQLCore: 0x156410>"
);
NSFilePath = "/var/mobile/Applications/appid/Documents/appname.sqlite";
NSUnderlyingError = "Error Domain=NSCocoaErrorDomain Code=4 \"The operation couldn\U2019t be completed. (Cocoa error 4.)\" UserInfo=0x181a30 {NSUnderlyingError=0x108ab0 \"The operation couldn\U2019t be completed. No such file or directory\"}";
}
I receive this error after removing and deleting an object:
[productList removeMProductObject:product];
[[delegate managedObjectContext] deleteObject:product];
[delegate saveContext];
I also noted that i also receive the error for the following scenarios(debugging):
1.
[productList removeMProductObject:product];
[delegate saveContext];
2.
[[delegate managedObjectContext] deleteObject:product];
[delegate saveContext];
3.
[[delegate managedObjectContext] deleteObject:product];
[productList removeMProductObject:product];
[delegate saveContext];
4.
[[delegate managedObjectContext] deleteObject:product];
[delegate saveContext];//error
[productList removeMProductObject:product];
[delegate saveContext];
5.
[productList removeMProductObject:product];
[delegate saveContext];//error
[[delegate managedObjectContext] deleteObject:product];
[delegate saveContext];
At times, i may pass around either the productList or a product object (both of type NSManagedObject) to other controllers, always using assign in the property and never retain. productList is an object which may contain many product objects.
I am able to create new objects(NSManagedObject), but when it comes to deleting them i get the error mentioned above. When running the application in the simulator i keep a close eye on the sqlite file. after attempting to delete an object(code above), i notice the .sqlite file is removed.
I have created a few Core Data iphone applications with no problem but i seem to be having an issue here. i don't believe i am doing anything out of the ordinary but perhaps i am missing a small detail, but i don't know what!
Why is my .sqlite file being deleted and resulting in this error message on save?
How can i find a more useful error message so i can determine the cause of this error?

Found the problem, but i'm not sure why it fixes it:
Before i would delete/remove the object i would delete the image associated with it(stored in the document's directory).
The image by default has no value(nil), but i would attempt to delete it anyway:
NSError *deleteError = nil;
[[NSFileManager defaultManager] removeItemAtPath:[DOCUMENTS_DIRECTORY stringByAppendingPathComponent:product.mPictureName] error:&deleteError];
#ifdef DEBUG_MODE
if(deleteError) {
NSLog(#"Error deleting image: %#", [deleteError description]);
}
else {
NSLog(#"Image %# deleted.", product.mPictureName);
}
#endif
if i instead do a nil check before attempting to remove the image like this, i get no error when i delete the managed object itself:
NSString *imageName = product.mPictureName;
if(imageName) {
NSError *deleteError = nil;
[[NSFileManager defaultManager] removeItemAtPath:[DOCUMENTS_DIRECTORY stringByAppendingPathComponent:imageName] error:&deleteError];
#ifdef DEBUG_MODE
if(deleteError) {
NSLog(#"Error deleting image: %#", [deleteError description]);
}
else {
NSLog(#"Image %# deleted.", imageName);
}
#endif
}
...
//delete NSManagedObject and save
i guess attempting to access the product's picture when it is nil makes it all invalid.

I had a similar issue that's worth reporting for any poor shmo that gets caught up in this issue. In my case I had a table view controller that handled row deletions by deleting the corresponding data from the data model. When I used the remove##ObjectName##Object method (stubbed out by the auto-generated NSManagedObject subclass), I would get an error similar to the one you reported.
When I instead used NSManagedObjectContext: deleteObject I didn't have a problem saving the context. But, I observed an exception being thrown with no indication of reason from the console.
It turns out the tableView method canEditRowAtIndexPath: was being called for the row corresponding to the newly deleted object. It was clear my row count needed to be updated prior to the OS calling this method. But, I don't care. I simply check to see whether the size of my array of managed objects can be indexed by the indexPath row.
if([managedObjSet.objects count] > indexPath.row) {
ManagedObject* obj = [managedObjectArray objectAtIndex:indexPath.row];
return ([obj.anotherManagedObjSet count] ==0);
}

Related

Lost data with multiple NSManagedObjectContexts on iOS7

I'm in the progress of updating an existing app for iOS 7 and I've been having some issues with Core Data saving objects. It's a fairly straightforward master-detail style data entry app that uses Core Data for the storage.
When adding a new record I use a second (temporary) managed object context to prevent the record appearing in the list before the record is saved. When a record is added and saved it is visible in the list as expected. However if I exit the app (it doesn't run in the background) and then restart it the record is no longer present. The record is present in the database (visible using the SQLite Manager Firefox plugin anyway), but it just doesn't show in the app.
I've managed to reproduce this using the code that Xcode produces when creating a new project. I've created a new master-detail application and ticked the Use Core Data box to get the example code, then made the following changes:
Add the following to MasterViewController.m
-(void)save:(NSManagedObjectContext*)context
{
if (context != [self.fetchedResultsController managedObjectContext])
{
NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter];
[dnc addObserver:self selector:#selector(addControllerContextDidSave:) name:NSManagedObjectContextDidSaveNotification object:context];
}
NSError *error;
if (![context save:&error])
{
abort();
}
if (context != [self.fetchedResultsController managedObjectContext])
{
NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter];
[dnc removeObserver:self name:NSManagedObjectContextDidSaveNotification object:context];
}
}
- (void)addControllerContextDidSave:(NSNotification*)saveNotification
{
[[self.fetchedResultsController managedObjectContext] mergeChangesFromContextDidSaveNotification:saveNotification];
}
Replace the supplied insertNewObject in insertNewObject with the following to create a new temporary context for adding
- (void)insertNewObject:(id)sender
{
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
context.persistentStoreCoordinator = [[self.fetchedResultsController managedObjectContext] persistentStoreCoordinator];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
[newManagedObject setValue:[NSDate date] forKey:#"timeStamp"];
// Save the context.
[self save:context];
}
I also set the app to not run in the background.
If I run this against iOS 6 it behaves as expected i.e. I tap Add and a new record appears, then exit and restart the app and the record is still present.
However if I run the same code against iOS 7 it doesn't work correctly. Tapping Add causes the new record to appear, but if I exit and them restart the app the record is not shown. As mentioned above it is present in the database however.
Interestingly, I've discovered that it might be in some way related to the change in the journaling mode of the SQLite database. If I add the following options in the call to addPersistentStoreWithType I get the expected behaviour running on iOS 7
NSDictionary *options = #{ NSSQLitePragmasOption : #{#"journal_mode" : #"DELETE"} };
So, to the questions (and thanks for reading this far!)
Has anyone else seen this behaviour (or is anyone able to reproduce it based on the description above)?
Is there something wrong with the way I am using a temporary context that I was just lucky with prior to iOS 7, or does this look like an issue with the Core Data framework on iOS 7?
Cheers
Neil
Edit 1:
In answer to Wain's question about saving the main MOC, I was under the impression that this isn't actually necessary because the data is already saved, the merge just updates the already saved changes from the temporary context in to the main context. That said the test code does contain the following methods and saveContext is called on shutdown, however [managedObjectContext hasChanges] returns false so nothing actually gets done at this point
-(void)applicationWillTerminate:(UIApplication *)application
{
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
}
-(void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil)
{
if ([managedObjectContext hasChanges])
{
if (![managedObjectContext save:&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.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
}
It seems to be fixed when you save your main context after merging changes:
- (void)addControllerContextDidSave:(NSNotification*)saveNotification
{
[[self.fetchedResultsController managedObjectContext] mergeChangesFromContextDidSaveNotification:saveNotification];
[self save:[self.fetchedResultsController managedObjectContext]];
}
UPDATE: this error was caused by using cache in NSFetchedResultsController. So, the data isn't lost, it's just not displayed by your NSFetchedResultsController. Further investigation is needed to find out why cache isn't updated when its MOC merges changes, but isn't saved.

Core Data: Not able to add persistent store to coordinator

I am making an app that displays organisms based around certain properties, such as Name, Color, Weight, etc. but those properties won't be known until run time. Which is why I am creating the NSManagedObjectModel programmatically. It seems I am able to initialize the model properly, as I use NSLog statement to show the organism entity's properties. But when I call the method:
[orgPersistentStoreCoordinator
addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil URL:storUrl options:nil error:&error]
It returns NO and I am getting an error in my persistent store coordinator method that says:
"Could not add persistent store:The operation couldn’t be completed. (Cocoa error 256.)"
I have tried turning these options on, but I still got the same error:
NSString * const NSMigratePersistentStoresAutomaticallyOption;
NSString * const NSInferMappingModelAutomaticallyOption;
Here is the full code:
- (NSPersistentStoreCoordinator *)orgPersistentStoreCoordinator {
if (orgPersistentStoreCoordinator != nil) {
return orgPersistentStoreCoordinator;
}
NSURL *storUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]
stringByAppendingPathComponent:#"organisms.sqlite"]];
NSError *error = nil;
orgPersistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:[self orgManagedObjectModel]];
NSLog(#"Entities: %#",[[self orgManagedObjectModel] entities]);
if (![orgPersistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil URL:storUrl options:nil error:&error]) {
/*Error for store creation should be handled in here*/
NSLog(#"Could not add persistent store:%#",[error localizedDescription]);
}
return orgPersistentStoreCoordinator;
}
And here is a snippet of how I am creating the ManagedObjectModel programmatically.
+ (NSManagedObjectModel *) orgManagedObjectModel
{
FieldGuide *f = [FieldGuide sharedFieldGuide];
NSManagedObjectModel *orgModel = [[NSManagedObjectModel alloc]init];
NSEntityDescription *organismEntity = [[NSEntityDescription alloc]init];
[organismEntity setName:#"OrganismCoreData"];
[organismEntity setManagedObjectClassName:#"OrganismCoreData"];
[orgModel setEntities:[NSArray arrayWithObject:organismEntity]];
NSMutableArray *orgEntityProperties = [[NSMutableArray alloc]init];
// 1. Name attributes
for (NameParameter *n in f.nameAttributes)
{
NSAttributeDescription *nameAttr = [[NSAttributeDescription alloc]init];
[nameAttr setName:n.name];
[nameAttr setAttributeType:NSStringAttributeType];
[orgEntityProperties addObject:nameAttr];
}
[organismEntity setProperties:orgEntityProperties];
return orgModel;
}
Finally, when I try to insert some organisms and save via the NSManagedObjectContext, the app terminates and displays this in the log:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.'
Any help or directions would be greatly appreciated, thanks!
Edit:
And yes, I have tried deleting the app from the simulator, clean target, and deleting the organisms.sqlite from the documents folder via finder.
Edit #2:
I forgot to add that the addPersistentStore method also returns another error:
2012-04-30 14:13:46.109 biodex[7510:14803] CoreData: error: (1) I/O error for database at /Users/junryandelacruz/Library/Application Support/iPhone Simulator/5.1/Applications/ACE957AF-2FC0-4EAF-B226-5019F70FAB90/Documents/organisms.sqlite. SQLite error code:1, 'near "OR": syntax error'
Looks like there is a mistake in your storeURL. This is the "Unknown File Read Error", usually to do with the path to the file.
From the documentation:
NSFileReadUnknownError = 256,
The second error certainly has nothing to do with adding the persistent store. Check your code for the "OR" predicate.

Core Data error: _Unwind_Resume called from function _PFFaultHandlerLookupRow in image CoreData

I'm getting this weird error from Core Date and I cant understand why.
The code below is executed when I delete a row of a UITableView.
I pass a string and an object to the method below and it fetches the article in a database table that has that string and has a foreign key to that object. Then I delete that object and reload the table.
- (void)deleteFavorite:(NSString *)link inFolder:(Favorites *)f {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *favsDecriptor = [NSEntityDescription entityForName:#"Favorites" inManagedObjectContext:context];
[request setEntity:favsDecriptor];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(belongsTo == %#) AND (link = %#)", f, link];
[request setPredicate:predicate];
NSError *error = nil;
NSMutableArray *fav = [[NSMutableArray alloc] init];
fav = [[context executeFetchRequest:request error:&error] retain];
if (![context save:&error]) {
NSLog(#"Cannot fetch the story from the fetch request.");
}
NSLog([[fav objectAtIndex:0] title]);
error = nil;
[context deleteObject:[fav objectAtIndex:0]];
if (![context save:&error]) {
NSLog(#"Can't delete the fav! %#", error);
}
}
The app instantly crashes and I get this message in the console.
But when I launch the app afterwards, the row has been deleted.
Detected an attempt to call a symbol in system libraries that is not present on the iPhone:
_Unwind_Resume called from function _PFFaultHandlerLookupRow in image CoreData.
Please help!
Thanks in advance to everyone!
This is probably related to a bug within Core Data itself. I had the same error come up (I asked about it here in SO) and my only fix was to change the keywords in the predicate that still allowed the same results. It took some experimenting to find the right combination. Not ideal, but that's the best answer I can offer based on my experience.
Is it possible that you are holding a reference to the delete object or that the deleted object is an observer and is getting a callback after its been deleted? I had something similar to this recently, though slightly different error message. In my case, I also crashed upon deletion (under some conditions) but when I relaunched the object-to-be-deleted had, in fact, been deleted.
If you haven't already done so, under the Run menu select Stop on Objective-C Exceptions. This helped me track down the root cause of my crash. In my case it was KVO observer getting callback of change of value of a property of deleted NSManagedObject.

Why can't I get the context from the delegate with this code?

I get an annoyingly vague error from the following code:
GFree2AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
context = [delegate managedObjectContext];
context is defined as a NSManagedObjectContext in the .h file and is the same in the delegate. All the right files seem to be included (except for <CoreData/CoreData.h> in the .m file - but the program throws the same issue whether its included or not. Its included in the header file.)
All the correct frameworks and stuff are included - when I started the project I selected "use coredata to manage data" or whatever it was. So surely there shouldn't be a problem?
Is there a better way to do what I'm trying to do? Basically I don't want to have to keep passing the context through different classes till I eventually want to use it (storing data is such a small part of my application).
In the console the error I get is:
2010-08-28 13:09:24.726 GFree2[3912:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'
...
terminate called after throwing an instance of 'NSException'
Program received signal: “SIGABRT”.
If I comment out the line: context = [delegate managedObjectContext]; then it all seems to work fine. (at the moment I haven't acctually used any coredata or anything so theres no more code related to it.
Thanks for anyone who can help, or provide some insight into this - its so complicated.
Edit: my app delegate file methods:
#pragma mark -
#pragma mark Core Data stack
/**
Returns the managed object context for the application.
If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
*/
- (NSManagedObjectContext *)managedObjectContext {
if (managedObjectContext != nil) {
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return managedObjectContext;
}
/**
Returns the managed object model for the application.
If the model doesn't already exist, it is created from the application's model.
*/
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel != nil) {
return managedObjectModel;
}
NSString *modelPath = [[NSBundle mainBundle] pathForResource:#"GFree" ofType:#"momd"];
NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return managedObjectModel;
}
/**
Returns the persistent store coordinator for the application.
If the coordinator doesn't already exist, it is created and the application's store added to it.
*/
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
NSURL *storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: #"GFree.sqlite"]];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil 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.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return persistentStoreCoordinator;
}
#pragma mark -
#pragma mark Application's Documents directory
/**
Returns the path to the application's Documents directory.
*/
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
EDIT AGAIN:
NSString *modelPath = [[NSBundle mainBundle] pathForResource:#"GFree" ofType:#"momd"];
NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
is the line where the error is. I'm not sure what type of file this is, but I'm sure it's obviously not finding it or something... :/ any ideas what I'm supposed to do?
#kiamlaluno - sorry for rolling back your edits, didn't mean to, just curious to see what you'd changed and thought that would show me... but it just completely removed them apparently. lol.
Edit build results:
DataModelCompile build/Debug-iphonesimulator/GFree2.app/GFree2.mom GFree2.xcdatamodel
cd "/Volumes/files/Gluten Free Cooking/Tom iPhone App/GFree2"
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/usr/bin/momc -XD_MOMC_TARGET_VERSION=10.6 "/Volumes/files/Gluten Free Cooking/Tom iPhone App/GFree2/GFree2.xcdatamodel" "/Volumes/files/Gluten Free Cooking/Tom iPhone App/GFree2/build/Debug-iphonesimulator/GFree2.app/GFree2.mom"
I believe that the problem is in persistentStoreCoordinator method in your GFree2AppDelegate.m file.
Could you update your question with the exact code of managedObjectModel, managedObjectContext and persistentStoreCoordinator methods from this file?
These methods are generated by the XCode when you check "Use Core Data for storage".
By the way, you shouldn't import .m files.
You're getting the error because GFree.momd doesn't exist. From the docs for NSURL's pathForResource:ofType: method:
Return Value The full pathname for the resource file or nil if the file could not be located.
GFree.momd is generated at build time from your .xcdatamodeld file (look in the Build Results for the line starting DataModelVersionCompile and expand it). Have you deleted or renamed that file?
Is it still listed in the Compile Sources section of your build target? (In Xcode expand Targets / [AppName] / Compile Sources).
Just noticed that your debug log says the app is called GFree2 but your code's looking for GFree.momd. Did you rename the project? If the data model file is now called GFree2.xcdatamodeld then you need to change the line that imports the momd file to use the new GFree2 name, too.

Updates not saving to DB and properties not firing faults

Two hopefully minor questions regarding CoreData that I've been unable to find answers to:
1) I have a faulted object. Accessing an attribute as a property is not firing the fault, accessing the same property via KVC IS firing the fault. Any idea why?
i.e. object.title returns nil and object is still faulted, but [object valueForKey:#"title"] returns the title and the object is no longer a fault.
2) Updates to existing records have stopped working. Add/Delete works. Add/Update share the same code path (one is passed the existing object, the other a newly inserted object). However Update wont work. The data in the updated object is correct and set to the new values and the save succeeds with no errors, but the record in the database remains unchanged. Any idea?
NB: There is only one NSManagedObjectContext
Cheers
couldn't tell much from your description without code.
however it looks like you have updated the object in ram but the update wasn't submitted to the database layer making the physical change.
EDIT:
Yes, "Add" and "Delete" is different from "edit/update" a record.
for performance reason mapped objects are saved in memory as entities when you doing manipulation against NSManagedObjectContext you are not coding against database entirely.
check the link below:
http://cocoawithlove.com/2010/02/differences-between-core-data-and.html
normal work flow:
load appropriate rows from a database
instantiate objects from these rows
make changes to the graph objects
that are now in memory
commit the changes back to the
database
This is my core data for saving.
AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
Tweet *newTweet = (Tweet *)[NSEntityDescription insertNewObjectForEntityForName:#"Tweet" inManagedObjectContext:app.managedObjectContext];
newTweet.status = status;
newTweet.post_date = theDate;
newTweet.post_id = post_id;
newTweet.sent_error = sent_error;
newTweet.sent_status = sent_status;
newTweet.screen_name = [Settings getActiveScreenName];
// SAVE
NSError* error = nil;
if (![app.managedObjectContext save:&error]) {NSLog(#"did this work?? = %# with userInfo = %#", error, [error userInfo]);}
I have this in my app delegate
- (void)applicationWillTerminate:(UIApplication *)application {
// need to check if TweetViewController is activel.
// User is writing a tweet.
UIViewController * topController = [navigationController visibleViewController];
if([topController isKindOfClass:[TweetViewController class]] ){
[Settings setObject:[(TweetViewController*)topController tweetText].text forKey:#"last_tweet_text"];
}
NSLog(#"good bye");
NSError *error;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Handle error.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1); // Fail
}
}
}
and this as well in AppDelegate
/**
Returns the persistent store coordinator for the application.
If the coordinator doesn't already exist, it is created and the application's store added to it.
*/
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
// ~/Library/Application Support/iPhone Simulator/User/
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: #"tweetv12.sqlite"]];
NSError *error;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
// Handle error
NSLog(#"cannot save data, change db name.");
}
return persistentStoreCoordinator;
}
I am also able to save delete and update data with this.