Can't save data to core data on main thread or private thread

128 Views Asked by At

Yesterday I was able to save records to core data but then I did a little bit of refactoring in my project to make my code cleaner(mostly code from my DTO where I encode / decode data with NSCoder and created separate files for my custom value transformers)

After that I noticed saving data stopped working, this is my code for adding:

 let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
    func add(pet: PetDTO) {
        let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
        managedObjectContext.perform {
            let newPet = PetEntity(context: managedObjectContext)
            
            newPet.id = Int64(pet.id)
            newPet.name = pet.name
            newPet.category = pet.category
            newPet.photoUrls = pet.photoUrls
            newPet.tags = pet.tags
            newPet.status = pet.status.rawValue
            do {
                try self.context.save()
            } catch {
                print(error)
            }
        }
    }

I It seems that I am missing something related to contexts. I created this managedObjectContext and from what I understand, I had to save data on this context, but nothing happens. I tried removing let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) and saving on main context but I had this error:

CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLSaveChangesRequestContext: 0x600000156640> , <shared NSSecureUnarchiveFromData transformer> threw while encoding a value. with userInfo of (null)
Error Domain=NSCocoaErrorDomain Code=134060 "A Core Data error occurred."

I managed to solve it only by adding another context and passing it to PetEntity.

So the question is: what am I doing wrong? Can I somehow merge contexts? I've seen a method for that but not sure if I need it.

Thanks

Update: Changed my code to this:

 do {
       try managedObjectContext.save()
        } catch {
        print(error)
     }

Just realized wasn't saving it on the right context. Now I have nilError and it still didn't save into the database. I think it happens because I get bad data from Json, my category field is sometimes nil and that's why it shows that error, am I right?

And about getting data from Core data, now I fetch it from main context, but the data is being saved on another context, what can I do here to fix this?

0

There are 0 best solutions below