iOS Core Data NSPersistentStoreCoordinator never opened database

Viewed 1434

I've got some weird problems with Core Data in my iOS which I cannot seem to reproduce, it just happens from time to time with some users that report it. The error I get from my iOS crash reports:

CoreData: -[NSPersistentStoreCoordinator _coordinator_you_never_successfully_opened_the_database_so_saving_back_to_it_is_kinda_hard:] + 56

Here is a screenshot (left out the product name):

enter image description here

The hard thing is that I don't get any search results on that error. Here is my (relevant) code:

saving:

-(void)save
{
    if(!self.horecaMOC.hasChanges)return;
    NSError *error;
    [self.horecaMOC save:&error];
    if(error)
    {
        NSLog(@"save error %@",error.localizedDescription);
    }
}

MOC:

-(NSManagedObjectContext*)horecaMOC
{
    if(!_horecaMOC)
    {
        NSPersistentStoreCoordinator *coordinator = self.horecaPSC;
        if (coordinator != nil) {
            _horecaMOC = [[NSManagedObjectContext alloc] init];
            [_horecaMOC setPersistentStoreCoordinator:coordinator];
        }
    }
    return _horecaMOC;
}

PSC:

-(NSPersistentStoreCoordinator*)horecaPSC
{
    if(!_horecaPSC)
    {
        NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"horeca.sqlite"];

        NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                                 [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
                                 nil];

        NSError *error = nil;
        _horecaPSC = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.horecaMOM];
        if (![_horecaPSC addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }

    }
    return _horecaPSC;
}

MOM:

-(NSManagedObjectModel*)horecaMOM
{
    if(!_horecaMOM)
    {
        NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"poi" withExtension:@"momd"];
        _horecaMOM = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    }
    return _horecaMOM;
}

It seems like the setup is OK here, because 99% of the time it works, but sometimes I get that error that I did not open the database. Since I can't debug it's hard to figure out what's the cause. Might the PSC nil? And why would that then be? Also, I know that a MOC should be bound to 1 thread only, and since I can't get it to crash I don't think there could be an issue regarding this?

Thanks for any advice!

0 Answers
Related