Search code examples
ioscore-dataswift4watchkit

Instance CoreData object without save it


I have an issue with CoreData which crashes my app.

enter image description here

This func crashes my app with this message:
enter image description here

If I do that it doesn't crash anymore (I changed course déclaration in my func):
enter image description here

And the concerned coreData object is:
enter image description here

What I am trying to do? When my app launches it get values from the iPhone. An array of string, another of Date, another of Int.

Like that:

Let tblNoms : [« English », « programming », « science »]
let tblDates : [08:25, 09:50, 07:30]
Let tblInt : [3, 8, 12]

So I take one of each to create a « Course » in the example here to create a course with

English 08:25 3, programming 09:50 8, sciences 07:30 12.

When « Course » are created put them in a array [Course].

Then I do a CoreData fetch request to see if my local data == the array I just created and update if it need. So you understand the array I create is not necessarily saved in CoreData. I just want to use this array of Course temporarily and then if I want save Course which are in into CoreData.

I hope you understand I was as clear as possible in my explanations


Solution

  • You can use a managed object context that is linked to an in-memory store; Objects created in this content will never be persisted to disk.

    Something like:

    lazy var persistentContainer: NSPersistentContainer = {
    
            let container = NSPersistentContainer(name: "MyModel")
    
            let description = NSPersistentStoreDescription()
            description.shouldInferMappingModelAutomatically = true
            description.shouldMigrateStoreAutomatically = true
            description.type = NSInMemoryStoreType
    
            container.persistentStoreDescriptions = [description]
    
            container.loadPersistentStores(completionHandler: { (storeDescription, error) in
                if let error = error as NSError? {
                    fatalError("Unresolved error \(error), \(error.userInfo)")
                }
            })
    
            return container
        }()