How to update specific data?

I created some data and saved into Realm. After that i want to update some data for specific user,

Code sample,

class Employee: Object {

@objc dynamic var id = 0

@objc dynamic var name = “”

@objc dynamic var salary = 0

@objc dynamic var city = “”

override static func primaryKey() -> String? {

return “id”

}

convenience init (empId: Int, empName: String, empSalary: Int, empCity: String) {

self .init()

self .id = empId

self .name = empName

self .salary = empSalary

self .city = empCity

}

}

func performOperation() {

    self.createAndSaveFirstData()
    self.createAndSaveSecondData()
    
    print("Data before update")
    self.retrieveAllData()
    
    self.updateData()
    
    print("Data after update")
    self.retrieveAllData()
}

func  createAndSaveFirstData()  {
    employee = Employee(empId: 1, empName: "Nivru", empSalary: 60000, empCity: "Bangalore")
    self.saveData()
}

func  createAndSaveSecondData()  {
    employee = Employee(empId: 2, empName: "Jigar", empSalary: 70000, empCity: "Pune")
    self.saveData()
}


func  saveData()  {
   try! realm.write {
        realm.add(employee)
    }
}


func  retrieveAllData()  {
    try! realm.write {
        let data = realm.objects(Employee.self)
        print("Retrived Data :\(data)")
    }
}


func  updateData()  {
         employee = Employee(empId: 1, empName: "Nivru", empSalary: 90000, empCity: "Bangalore")
         self.saveData()
}

in above sample i want to update only salary of empId 1 , how can i update it

The code formatting is a little off and I am not sure the question is clear but it appears you would like to update the salary for an employee saved in Realm (?)

I see you’re using primary keys so if you know the primary key of the employee’s salary you want to update, create a new employee in code, set the updated salary and id and then write to realm using .modified. Here’s the code:

let emp = Employee()
emp.salary = 80000
emp.id = 1

try! realm.write {
   realm.add(emp, update: .modified)
}

@jay , Thanks for reply but its not working.

func updateData() {
try! realm.write {
employee.id = 1
employee.salary = 80000
}
}

func saveAfterUpdate() {
    try! realm.write {
        realm.add(employee, update: .modified)
    }
}

I am getting below exception,
Terminating app due to uncaught exception ‘RLMException’, reason: 'Primary key can’t be changed after an object is inserted.'