Arthur Ferreira
Arthur Ferreira

Reputation: 321

Saved Core Data does not persist after app closes 80% of the time

I started dealing with Core Data lately, and in my tests, I've found that about 20% of the time the data actually gets saved to the DB. The rest of the time, it's only saved temporarily, while the app is running. If I restart, the last data I saved gets lost.

Does anyone know what the problem could be?

Here's the code:

//Save data
NSEntityDescription *users = [NSEntityDescription insertNewObjectForEntityForName:@"Users" inManagedObjectContext:document.managedObjectContext];
[users setValue:@"Name Test" forKey:@"name"];
[users setValue:[NSNumber numberWithInt:20] forKey:@"age"];
[users setValue:@"Some Country" forKey:@"location"];


//Debugging
//no error ever shows up
NSError *error;
if(![document.managedObjectContext save:&error]) {
    NSLog(@"Error: %@", error);
}

//this is just to show that the problem may not be with my UIManagedDocument (self.document), since the NSLog never gets called.
if(self.document.documentState != UIDocumentStateNormal) {
    NSLog(@"Document is not opened");
}
//End of debugging


//Fetch all the data from the entity
NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"Users"];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
fetch.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];

NSArray *results = [document.managedObjectContext executeFetchRequest:fetch error:nil];
NSLog(@"Results on the database: %d", [results count]);

document is the same thing (at least I hope so, in most of the cases) as self.document; it's just an argument of the method where this code is located.

Here's the code for my .h and .m:

.h:

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>

@interface CoreDataViewController : UIViewController

@property (nonatomic, strong) UIManagedDocument *document;

@end

.m:

#import "CoreDataViewController.h"

@implementation CoreDataViewController
@synthesize document = _document;

- (void)fetchStuff:(UIManagedDocument *)document {

    //Save data
    NSEntityDescription *users = [NSEntityDescription insertNewObjectForEntityForName:@"Users" inManagedObjectContext:document.managedObjectContext];
    [users setValue:@"Name Test" forKey:@"name"];
    [users setValue:[NSNumber numberWithInt:20] forKey:@"age"];
    [users setValue:@"Some Country" forKey:@"location"];


    //Debugging
    //no error ever shows up
    NSError *error;
    if(![document.managedObjectContext save:&error]) {
        NSLog(@"Error: %@", error);
    }

    //this is just to show that the problem may not be with my UIManagedDocument (self.document), since the NSLog never gets called.
    if(document.documentState != UIDocumentStateNormal) {
        NSLog(@"Document is not opened");
    }
    //End of debugging


    //Fetch all the data from the entity
    NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"Users"];
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
    fetch.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];

    NSArray *results = [document.managedObjectContext executeFetchRequest:fetch error:nil];
    NSLog(@"Results on the database: %d", [results count]);
}

- (void)useDocument {
    if(![[NSFileManager defaultManager] fileExistsAtPath:[self.document.fileURL path]]) {
        [self.document saveToURL:self.document.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){
            if(success == YES) NSLog(@"created");
            [self fetchStuff:self.document];
        }];
    } else if(self.document.documentState == UIDocumentStateClosed) {
        [self.document openWithCompletionHandler:^(BOOL success) {
            if(success == YES) NSLog(@"opened");
            [self fetchStuff:self.document];
        }];
    } else if(self.document.documentState == UIDocumentStateNormal) {
        [self fetchStuff:self.document];
    }
}

- (void)setDocument:(UIManagedDocument *)document {
    if(_document != document) {
        _document = document;
        [self useDocument];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if(!self.document) {
        NSURL *url = [[[NSFileManager defaultManager]URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
        url = [url URLByAppendingPathComponent:@"Database"];
        self.document = [[UIManagedDocument alloc]initWithFileURL:url];
    }
}

@end

Note: There's also my data model, which has an entity called "Users", with the attributes age, location, name.

Upvotes: 1

Views: 4590

Answers (3)

Arthur Ferreira
Arthur Ferreira

Reputation: 321

The data was being saved sometimes because of the autosaving, which happens each X (maybe 10, I need to check on documentation) seconds. To force the save, I should've used this:

[documentation saveToURL:documentation.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:^(BOOL success) {
if(success == YES) NSLog(@"Awesome, it's saved!");
}];

Although it works fine adding this code to fetchStuff:, it'd be better to implement this when the user exits the screen, since it could be automatically saved via autosave.

Upvotes: 7

user2823580
user2823580

Reputation:

    Record *newentry = [NSEntityDescription insertNewObjectForEntityForName:@"Record" inManagedObjectContext:self.mManagedObjectContext];
    newentry.code = entryStr;
    NSError *error;
    if ([self.mManagedObjectContext save:&error])
    {
        NSLog(@"save successfully");
    }
    else
    {
        NSLog(@"fail to save");
    }

Upvotes: 0

Jody Hagins
Jody Hagins

Reputation: 28409

You should not call save on the UIManagedDocument MOC. Here's an edited version of your code. Please try it.

//Save data
NSEntityDescription *users = [NSEntityDescription insertNewObjectForEntityForName:@"Users" inManagedObjectContext:document.managedObjectContext];
[users setValue:@"Name Test" forKey:@"name"];
[users setValue:[NSNumber numberWithInt:20] forKey:@"age"];
[users setValue:@"Some Country" forKey:@"location"];

// Removed save on UIMDMOC - We let auto-save do the work
// However, we have to tell the document that it needs to 
// be saved. Now, the changes in the "main" MOC will get pushed
// to the "parent" MOC, and when appropriate, will get save to disk.
[document updateChangeCount:UIDocumentChangeDone];

if(self.document.documentState != UIDocumentStateNormal) {
    NSLog(@"Document is not opened");
}    

//Fetch all the data from the entity
NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"Users"];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
fetch.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];

NSArray *results = [document.managedObjectContext executeFetchRequest:fetch error:nil];
NSLog(@"Results on the database: %d", [results count]);

OK... That was not too painful... just removed the call to save, and replaced it with a call that tells the UIManagedDocument that some changes have been made, and need to be saved.

Upvotes: 2

Related Questions