Search code examples
iosswiftswift2realm

Realm Query to variable and results


With the following code I'm currently trying to search to my realm db if the id eventId1 is somewhere inside the database in the column realmeventID and if it is to print true. But with I get no result even if the statement I know is true!

override func viewDidLoad() {
    super.viewDidLoad()
    let realm = try! Realm()
    var tanDogs = realm.objects(eventsNewSaved2.self)
    let predicate = NSPredicate(format: "realmeventID == %@", eventId1)

    if predicate == true {
        print("true")
    }
}

Am I missing something important here??


Solution

  • To query using NSPredicate, you can do the following:

    let predicate = NSPredicate(format: "realmeventID == %@", eventId1)
    let results = realm.objects(eventsNewSaved2.self).filter(predicate)
    

    This can also be written as follows more easily.

    let results = realm.objects(eventsNewSaved2.self).filter("realmeventID == %@", eventId1)
    

    Whether the result is present you can see in the following manner.

    if !results.isEmpty {
        // The results is not empty
    }
    

    or,

    if let event = results.first {
        // The results is not empty because there is a first element
    }
    

    So, is the following code you would like to?

    let realm = try! Realm()
    let results = realm.objects(ToDoList.self).filter("realmeventID == %@", eventId1)
    
    if !results.isEmpty {
        print("true")
    }