Search code examples
swiftrealm

Swift: Filtering records using Realm


I'm new to Realm and I need help. First things first, my Realm object looks like so:

class RegistrationInf: Object {
    dynamic var RValCode = ""
    dynamic var RIsConfirmed = false
}

I have a PHP script that returns JSON data containing the validation code, which I insert into the Realm database using the function below:

func RegisterToDatabase(Valcode:String, IsConfirmed:Bool = false){

    let loRegistrationInf = RegistrationInf()

    let realm = try! Realm()

    if IsConfirmed {
        let loReg = realm.objects(RegistrationInf.self).filter("RValCode == \(Valcode)").first
        try! realm.write {
            loReg?.RIsConfirmed = IsConfirmed
        }
        self.loIsConfirmed = IsConfirmed
    }
    else {
        loRegistrationInf.RValCode = Valcode
        loRegistrationInf.RIsConfirmed = IsConfirmed

        try! realm.write {
            realm.add(loRegistrationInf)
        }
    }
}

Then when the user receives the SMS containing the code, they enter and confirm it, and the above function is called again, only this time the the second parameter's value is true.

When the code comes to the following line:

let loReg = realm.objects(RegistrationInf.self).filter("RValCode == \(Valcode)").first

I get an exception telling me:

Terminating app due to uncaught exception 'Invalid value', reason: 'Property 'RValCode' is not a link in object of type 'RegistrationInf''

What am I missing here?


Solution

  • Your filter should be .filter("RValCode == %@", Valcode). Using Swift's string interpolation here produces an invalid query due to the string not being quoted (which is not required when using NSPredicate format syntax).