UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: CoreData stopped persisting data anymore

Forums > SwiftUI

Hello. I'm working on an app after all Core Data knowledge from Paul's course. After some days of work, two days ago, I had to make little minor changes on my .xcdatamodel. After doing so, the app runs as usual, but no data is persisted.

As general swift files for views and so haven't been changed at all, I've double (triple...)-checked files related to Core Data configuracion.

  1. xcdatamodel file name is "Comping". Imagelink:

https://www.dropbox.com/s/2xmo6roq86xan7g/Captura%20de%20Pantalla%202022-08-17%20a%20las%2013.12.59.png?dl=0https://

  1. DataController file, with the same name:
import Foundation
import CoreData
import SwiftUI

class DataController: ObservableObject {

    let container = NSPersistentContainer(name: "Compin")

    init() {
        container.loadPersistentStores { description, error in
            if let error = error {
                print("No pudo cargarse Core Data: \(error.localizedDescription)")
            }

            self.container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
        }
    }
}
  1. Main app file, with the proper code for Core Data:
import SwiftUI

@main
struct CompinApp: App {

    @StateObject private var dataController = DataController()

    var body: some Scene {
        WindowGroup {
            MainView()
                .environment(\.managedObjectContext, dataController.container.viewContext)
        }
    }
}
  1. All Core Data entities marked as "Manual/none" class generation, on its place, as follows (this is one of them):
import Foundation
import CoreData

extension Alumno {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Alumno> {
        return NSFetchRequest<Alumno>(entityName: "Alumno")
    }

    @NSManaged public var correo: String?
    @NSManaged public var foto: String?
    @NSManaged public var id: UUID?
    @NSManaged public var marcado: Bool
    @NSManaged public var nacimiento: Date?
    @NSManaged public var nombre: String?
    @NSManaged public var notas: String?
    @NSManaged public var telefono: String?
    @NSManaged public var timestamp: Date?
    @NSManaged public var cursoRelacionado: Curso?
    @NSManaged public var ensayosRelacionados: NSSet?
    @NSManaged public var especialidadRelacionada: Especialidad?
    @NSManaged public var obrasRelacionadas: NSSet?
    @NSManaged public var tutorRelacionado: Tutor?

}

// MARK: Generated accessors for ensayosRelacionados
extension Alumno {

    @objc(addEnsayosRelacionadosObject:)
    @NSManaged public func addToEnsayosRelacionados(_ value: Ensayo)

    @objc(removeEnsayosRelacionadosObject:)
    @NSManaged public func removeFromEnsayosRelacionados(_ value: Ensayo)

    @objc(addEnsayosRelacionados:)
    @NSManaged public func addToEnsayosRelacionados(_ values: NSSet)

    @objc(removeEnsayosRelacionados:)
    @NSManaged public func removeFromEnsayosRelacionados(_ values: NSSet)

}

// MARK: Generated accessors for obrasRelacionadas
extension Alumno {

    @objc(addObrasRelacionadasObject:)
    @NSManaged public func addToObrasRelacionadas(_ value: Obra)

    @objc(removeObrasRelacionadasObject:)
    @NSManaged public func removeFromObrasRelacionadas(_ value: Obra)

    @objc(addObrasRelacionadas:)
    @NSManaged public func addToObrasRelacionadas(_ values: NSSet)

    @objc(removeObrasRelacionadas:)
    @NSManaged public func removeFromObrasRelacionadas(_ values: NSSet)

}

extension Alumno : Identifiable {

}

As you can see, everything seems to be ok, but no data persists after app closing. Any idea for further research?

Thanks!

1      

You did not mention, I'm guessing you tried this?

Did you delete the older application on your test device, and perform a clean build? This may clear old leftovers that may interfere with your updated model.

1      

Thank you very much for your quick response.

Yes: I deleted and reinstaled many times the app, both on my iPhone and XCode simulators. Even deleted every simulator and reinstaling them again. EVEN deinstaling XCode, deleting all related files, preferences and so, and reinstalling all again, just in order to be sure that every possible duplicate related to Core Data model or so is deleted.

Without sucess. Is there any obscure folder where any old-model could be hidden to run this problem? But in that case, how is it possible that in my iPhone happens the same, even aftet deleting the app?

Any further ideas for research? Thank you!

1      

Any further ideas for research? Thank you!

I think we were all hoping that this year's WWDC would have brought us a more Swifty version of CoreData. This was on many folk's wish list.

@twoStraws touches upon CoreData, but for advanced answers, most advice is to check out Donny Wal's book. Also Mark Moeykens wrote a Core Data Quick Start which mentions another of his Core Data books Core Data Mastery in SwiftUI. Perhaps you can volunteer to proof read an early version of his new book.

See -> Practical Core Data
See -> Core Data Quick Start

1      

Ok. Thanks! I'll have a look.

The misterious thing is that it has worked ok for weeks until that moment. And that all CD configuration, model, and so, is correct.

1      

Moreover: if I recreate the app from the ground, it doesn't work, also! It seems that it is trying to write and fetch from any obscure data with the same naming ☹

1      

I had the same issue. If you look through all the console warnings core data generates , you'll see some errors pertaining this. You'll just need to force Xcode to re-generate the data models and not reuse them. What helped me was the following:

  1. Reset both private and public environments in the icloud dashboard
  2. Close Xcode and simulator
  3. Delete all the contents inside ~/Library/Developer/Xcode/UserData/Previews/Simulator Devices/.
  4. Kill all instances of the iOS Simulator:
killall -9 com.apple.CoreSimulator.CoreSimulatorService.
  5. Restart Xcode.
  6. Open your project again, clean build folder (⌘⇧K), and run your project

hope this helps!

EDIT No Cloud, you can skip the first step

1      

Thats it!! Thanks!

As I supossed, something was "in the background". Great..

1      

you're welcome! Mark the topic as solved....

1      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.