Saurabh
Saurabh

Reputation: 745

Unable to save values to Core Data

I am trying to store data to Core-Data in AppDelegate itself and then fetch that data from ViewController. For some reason, it is not getting saved in Core-Data. I have tried searching for this issue on the internet but did not get any specific solution. I have pasted the code below -

AppDelegate.swift

func saveContext () {
    let context = persistentContainer.viewContext
    print(context)
    let entity = NSEntityDescription.entity(forEntityName: "Msg", in: context)
    print(entity)
    let new = NSManagedObject(entity: entity!, insertInto: context)
    print(new)
    print(getData.alert_message)
    new.setValue(getData.alert_message, forKey: "title")
    do {
        try context.save()
        print("save")
        print(new.value(forKey: "title"))
    } catch {
        let nserror = error as NSError
        fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
    }  
}

Console Output

enter image description here

Upvotes: 0

Views: 1025

Answers (4)

Gulfam Khan
Gulfam Khan

Reputation: 1089

In my case i was trying to update data saved in core data. but every time it was returning the old data ( not the updated version )

Saved successfully message was being printed in console same as yours

Here are some simple steps that finally solved my problem

  • fetch data with a NSFetchRequest
  • save data into a temp variable
  • delete old data from core data
  • modify data from temp variable
  • and finally save context

Here is my update data function

func updateUserData(_ userDetails: UserModel) {

    let request = UserDetails.fetchRequest() as NSFetchRequest<UserDetails>
    do {
        let result = try persistentContainer.viewContext.fetch(request)
        if let data = result.first?.userData as Data? {
            var loginModel = LoginModel(data: data)
            loginModel?.user = userDetails
            self.clearUserData() //deleting old data
            self.userLoginData = loginModel?.jsonData
        }
    }catch let error as NSError {
        debugPrint(error.localizedDescription)
    }

}

Upvotes: 0

Dhaval Gevariya
Dhaval Gevariya

Reputation: 920

 Hear I have Set My Own Solution, Hope This help You


let contex = ((UIApplication.shared.delegate) as! AppDelegate).persistentContainer.viewContext

func SaveData()
 {
 let entity = NSEntityDescription.insertNewObject(forEntityName: "Employee", into: contex);
        entity.setValue(txtname.text, forKey: "empname") // txtname.text is My TexField name 
        entity.setValue(txtadd.text, forKey: "empadd");
        do
        {
            try contex.save();
        }
        catch
        {

        }
 }

Upvotes: 1

Ashutos Sahoo
Ashutos Sahoo

Reputation: 82

I think you are not giving values to all attributes of the entity so check that first.

try something like

new.setValue(msgdata, forKey: "msgdata")

//msgdata is what you want to save on Coredata entity

//try something like this

Upvotes: 0

Govaadiyo
Govaadiyo

Reputation: 6082

You can fetch record from the entity by NSFetchRequest

Try with below method, You just need to pass name of the entity as argument of the function.

func getAllRecordFromTableWhere(_ tableName: String) -> [NSManagedObject]? {
    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: tableName)
    do {
        return try managedContext.fetch(fetchRequest)
    } catch let error as NSError {
        print("Could not fetch. \(error), \(error.userInfo)")
    }
    return nil
}

and call function like

if let arrayOfData = DBHelper.getAllRecordFromTableWhere("Msg") {
    print(arrayOfData)
}

Upvotes: 1

Related Questions