Core Data error: The database appears corrupt

I'm working on a Cloudkit sync with my Core Data app. I made a NSOperation to update my local store with records downloaded from the cloud.


When I initialize my custom operation, I create a private NSManagedObjectContext.

It's created like so in my Core Data Stack class:


func createBackgroundManagedContext() -> NSManagedObjectContext {

   let backgroundManagedObjectContext = NSManagedObjectContext.init(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
   backgroundManagedObjectContext.parentContext = self.managedObjectContext
   backgroundManagedObjectContext.undoManager = nil
   return backgroundManagedObjectContext
}


Later, when my custom operation main() function is called, and I'm trying to insert new managed object into my context, i'm recieving this error:


2016-05-12 22:50:45.115 MyApp[5026:1496475] Core Data: error: -executeRequest: encountered exception = The database appears corrupt.  (invalid primary key) with userInfo = {
    NSFilePath = "/var/mobile/Containers/Data/Application/F126328C-5F17-48DA-955A-4D489C6B8FF2/Documents/MyAppCoreData.sqlite";
}
2016-05-12 22:50:45.122 MyApp[5026:1496475] Core Data: error: -executeRequest: encountered exception = The database appears corrupt.  (invalid primary key) with userInfo = {
    NSFilePath = "/var/mobile/Containers/Data/Application/F126328C-5F17-48DA-955A-4D489C6B8FF2/Documents/MyAppCoreData.sqlite";
}
2016-05-12 22:50:45.138 MyApp[5026:1496475] Core Data: error: -executeRequest: encountered exception = The database appears corrupt.  (invalid primary key) with userInfo = {
    NSFilePath = "/var/mobile/Containers/Data/Application/F126328C-5F17-48DA-955A-4D489C6B8FF2/Documents/MyAppCoreData.sqlite";
}
Error Domain=NSCocoaErrorDomain Code=259 "The file “MyAppCoreData.sqlite” couldn’t be opened because it isn’t in the correct format." UserInfo={NSFilePath=/var/mobile/Containers/Data/Application/F126328C-5F17-48DA-955A-4D489C6B8FF2/Documents/MyAppCoreData.sqlite, NSUnderlyingException=The database appears corrupt.  (invalid primary key)}


Here is the part of my main function:


    let backgroundContext : NSManagedObjectContext
    override func main() {
        print("UpdateLocalStoreOperation")
        backgroundContext.performBlock {
  
            if let addOrUpateArray = self.recordsToUpdate where addOrUpateArray.count > 0 {
           
                let recordsToUpdateRequest = NSFetchRequest(entityName: "MyEntity")
                for objectRecord in addOrUpateArray {
          
                    recordsToUpdateRequest.predicate = NSPredicate(format: "recordName == %@", anchorRecord.recordID.recordName)
          
                    var existingObject : MyEntity?
                    do{          
                        existingObject = try self.backgroundContext.executeFetchRequest(recordsToUpdateRequest).first as? MyEntity
              
                    } catch let error as NSError{
                        fatalError("CoreDataStack - update and insert backgroundManagedObjectContext ERROR: \(error.localizedDescription)")
                    }
          
          
                    if let object = existingObject {
                        object.updateWithCloudRecord(objectRecord)
                    }
                    else {
              
                        let description = MyEntity.entityDescriptionForContext(self.backgroundContext)
              
                
                        let newObject = MyEntity(entity:  description, insertIntoManagedObjectContext: self.backgroundContext)
                        print("Error on below this print")
                        newObject.updateFillWithCloudValues(objectRecord)
                        print("Error above this print")
                    }
          
                }
....
//The rest of the method (dealing with deleted object, saving context)    


Although I'm getting this error, new object is saved. I'm not sure, what i'm doing wrong and how I need to fix this issue. Or maybe I can ignore it (but it would be the worst scenarion in my opinion).


My method updateFillWithCloudValues makes additional fetch request to the core data.


let request = NSFetchRequest(entityName: "MyEntity")
request.sortDescriptors = [NSSortDescriptor(key: "index", ascending: false)]
request.fetchLimit = 1
request.propertiesToFetch = ["index"]
         
print("Error here")
do{
   if let lastObject = try managedObjectContext?.executeFetchRequest(request).first as? MyEntity {
      self.index = NSNumber(integer: lastAnchor.index!.integerValue + 1)
   }
   else{
      self.index = 0
   }
} catch let error as NSError{
    print(error)
}


It's something with my context? Could someone explain what is going on here and why my actions is cause error.

Core Data error: The database appears corrupt
 
 
Q