ioscore-datanspersistentstoreios8.1

CoreData PersistentStorage failed to create file


I have a problem on iOS 8.1 with CoreData. On my device I always get this error while the code runs fine on every simulator:

Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)" UserInfo=0x15e62bd0 {reason=Failed to create file; code = 1} with userInfo dictionary {
reason = "Failed to create file; code = 1";
}

I already tried to delete the app from my device. I successfully tried to manually create a text file. Here is the code snippet which causes the error:

- (NSPersistentStoreCoordinator*) persistentStoreCoordinator {
  NSError* error = nil;
  NSURL* storeURL = [[[NSBundle mainBundle] resourceURL] URLByAppendingPathComponent: @"users.sqlite"];

  if (_persistentStoreCoordinator != nil)
    return _persistentStoreCoordinator;

  _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
  if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
    error = nil;
    [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil];
    [_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];
  }

  return _persistentStoreCoordinator;
}

EDIT:

Thanks for your answer jrturton. The solution is

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSURL* storeURL = [NSURL fileURLWithPath:[documentsDirectory stringByAppendingString:@"/users.sqlite"] isDirectory:NO];

Solution

  • Your app's bundle is read-only on the device, but not on the simulator.

    When you're creating storeURL you are creating a URL that points to the app's bundle. You should be using the documents directory instead.