Update an object on core data swift 4

16,175

Solution 1

Please read the error message. It's very clear. In setValue you are passing a String (via String Interpolation) rather than expected Int or NSNumber

object.setValue(jobId, forKey: "jobId")

or

object.setValue(NSNumber(value: jobId), forKey: "jobId")

But the best and recommended way is dot notation

object.jobId = jobId

Solution 2

Update Object to core data

@IBAction func buttonUpdate(_ sender: Any) {
        let entity = NSEntityDescription.entity(forEntityName: "Students", in: managedContext)
        let request = NSFetchRequest<NSFetchRequestResult>()
        request.entity = entity
        let newName = UserDefaults.standard.value(forKey: "new") as! String
        let predicate = NSPredicate(format: "(name = %@)", newName)
        request.predicate = predicate
        do {
            let results =
                try managedContext.fetch(request)
            let objectUpdate = results[0] as! NSManagedObject
            objectUpdate.setValue(txtName.text!, forKey: "name")
            objectUpdate.setValue(txtPhone.text!, forKey: "phone")
            objectUpdate.setValue(txt_Address.text!, forKey: "address")
            do {
                try managedContext.save()
                labelStatus.text = "Updated"
            }catch let error as NSError {
              labelStatus.text = error.localizedFailureReason
            }
        }
        catch let error as NSError {
            labelStatus.text = error.localizedFailureReason
        }

    }
Share:
16,175

Related videos on Youtube

Sptibo
Author by

Sptibo

Updated on June 04, 2022

Comments

  • Sptibo
    Sptibo almost 2 years

    I have several items of jobs in core data entity whose jobId is -1. I need to fetch all those items and update jobId by proper ids which are in my object that is passed in updateMyJobs method. I haven't extracted NSManagedObject class to work on core data (i.e.- I've checked the entity as Class definition)

    Here's my code:

    func updateMyJobs(jobId: Int){
        managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "DBJobsNearBy")
        fetchRequest.predicate = NSPredicate(format: "jobId = '-1'")
        let result = try? managedObjectContext.fetch(fetchRequest)
        let resultData = result as! [DBJobsNearBy]
        for object in resultData {
            print(object.jobId)
            if object.jobId == -1 {
                object.setValue("\(jobId)", forKey: "jobId")
            }
        }
        do {
            try managedObjectContext.save()
            print("saved!")
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
        }
    }
    

    I passed some integer value and call the above method to update the item like this.

    DatabaseHandler.shared.updateMyJobs(jobId: 222)
    

    Error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "jobId"; desired type = NSNumber; given type = Swift._NSContiguousString; value = 222.'

    I'm trying to set new jobId to the related object in core data entity. Is it necessary to extract NSManagedObject Class or not. Please someone help me to do this. Thank You.

    • pbasdf
      pbasdf about 6 years
      Are you saying that jobId is a key to a separate entity, with a relationship to DBJobsNearBy, and you want to set that relationship? If so, please show your data model.
    • Sptibo
      Sptibo about 6 years
      There is no relationship to DBJobsNearBy. I've multiple jobId fetched from web and want to update them on coredata jobIds whose ids are -1.
  • Sptibo
    Sptibo about 6 years
    This code updated the jobId but it updated same value to every item. Please help me to update on the basis of objectId so that all jobId will update with their proper ids.
  • vadian
    vadian about 6 years
    Your code updates all objects in resultData with the jobId parameter.
  • Sptibo
    Sptibo about 6 years
    Yet it updates all objects but it updates all objects by last jobId. I've multiple jobId fetched from web and want to update them on coredata jobIds whose ids are -1
  • vadian
    vadian about 6 years
    But there is only one single jobID as parameter. If you want to change multiple different values you need to change the logic.
  • Sptibo
    Sptibo about 6 years
    Please tell me the logic.
  • vadian
    vadian about 6 years
    I cannot read your mind. It's unclear what you are going to accomplish.