2
votes

This is the object I created with primary key username and the error when I try to run the add object code.

class Login_item: Object {
dynamic var username = String()
dynamic var password = String()

override static func primaryKey() -> String? {
    return "username"
}

}

This is the code that add new object and update object.

func save_login_info() {
    let new_login_entry = Login_item()

    new_login_entry.username = Username.text!
    new_login_entry.password = Password.text!

    let realm = try! Realm()
    try! realm.write {
        realm.add(new_login_entry)
        print("Login info save as: \(Realm.Configuration.defaultConfiguration.fileURL!)")
    }

    try! realm.write {
        realm.add(new_login_entry, update: true)
    }
}

Error I got when execute the code.

fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=10 "Migration is required due to the following errors: - Property 'username' has been made a primary key." UserInfo={NSLocalizedDescription=Migration is required due to the following errors: - Property 'username' has been made a primary key., Error Code=10}: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-703.0.18.8/src/swift/stdlib/public/core/ErrorType.swift, line 54

1
Hello! Please, insert your code in your post as text, not as screenshot! And we will try to watch it. Thank you!Shadow Of
Did you run the code, then change your data model or add the primary key after an object had been saved? Try resetting the simulator settings so that it removes all traces of any previous Realm databases, then run it again.Haligen
Tried everything possibleNicky
I know I threw the exact error when I defined my model, ran the project, then went back and set one of the properties in my model to a primary key. The only thing that fixed it was to reset all the sim settings on each device I had run my code on, and to erase the app from any hard devices I had used. Then everything ran fine, but you could always try actually doing a migration linkHaligen
@Haligen thanks i delete every realm file in the core simulator and it worksNicky

1 Answers

0
votes

Yeah you need to add migration instruction when you change the model, thats what the error message is describing.

let config = Realm.Configuration(schemaVersion: 1, migrationBlock: { migration, oldSchemaVersion in
  if oldSchemaVersion < 1 {

  }
})

The 1 in the code represents the current version, and every time you make any changes to the code you need to increase the version number and do any changes to the data that you want to.

You can read more about it here