Jesper Johansson Jesper Johansson - 10 days ago 5
iOS Question

Core Data - can't fetch, without first inserting

I've added a Data Model and Core Data to my existing project and I can successfully write objects and save them/insert, but I can not just fetch whats in the database. What am I doing wrong? Or have I misunderstood how Core Data works?

I can insert an object and then get the desired result with the code below - but I can't retrieve the objects without using insert first. I want to store a "token" so the app remembers it.

let dc = DataController()
let moc = dc.managedObjectContext

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Token")
//fetchRequest.returnsObjectsAsFaults = false

do {
let entities = try moc.fetch(fetchRequest) as! [NSManagedObject]
print(entities.count) // prints 0
print(entities) // prints []
for entity in entities {
print(entities.count) // these dont work because of 0 results
print(entity) // these dont work because of 0 results
}
} catch {
print("could not fetch")
}


Debug log:

0
[]
CoreData: annotation: Connecting to sqlite database file at "/Users/xxxx/Library/Developer/CoreSimulator/Devices/1231231-123123-123123-123123-123123123/data/Containers/Data/Application/123123-123123-123123-123123-123123123/Documents/DataModel.sqlite"
CoreData: sql: SELECT TBL_NAME FROM SQLITE_MASTER WHERE TBL_NAME = 'Z_METADATA'
CoreData: sql: pragma recursive_triggers=1
CoreData: sql: pragma journal_mode=wal
CoreData: sql: SELECT Z_VERSION, Z_UUID, Z_PLIST FROM Z_METADATA
CoreData: sql: SELECT TBL_NAME FROM SQLITE_MASTER WHERE TBL_NAME = 'Z_MODELCACHE'
CoreData: annotation: Disconnecting from sqlite database.


I've opened the sqlite file and the objects I've inserted before exist there.

Answer

You can do like this for retrieving data.

func retriveSaveData(){

    let request:NSFetchRequest<TestData> = TestData.fetchRequest()
    do {
        let data = try managedObjectcontext.fetch(request) as [TestData]

        if let str = data.first?.name{
            // Your retrieve data
            print(str)
        }
    }catch{
        let error  = error as NSError
        print("\(error)")
    }
}

for saving and updating data.

 func saveToDataBase(data:[TestData]){
        for data1 in data{

            let request:NSFetchRequest<TestData> = TestData.fetchRequest()
            do {
                let count = try managedObjectcontext.count(for: request)
                if count == 0 {
                    // save data according to your requirement.
                    print(data1)
                }else{

                    //if anything you want to update then wright here
                }

            }catch{
                let error  = error as NSError
                print("\(error)")
            }
        }
    }

Hope it will help you