Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm search Database with Predicate in Swift 2

I write an (Mac)App in Swift2 which should search a Realm database of Teachers with a sepcific subject. The Definition for the Teacher Object in realm looks like this:

class Teacher: Object {
     var subjects = List<Subject>()
}

This class is very complex so I deleted some lines...

Here's the function that should filter the Database for Teachers with Specific subjects and give only the Teacher names back (as String Array: [String]):

func getAllTeacherNamesForSubject(subject: String) -> [String] {
    // Open Database
    let realm = openRealmDatabase()

    // Or open it this way:
    // RLMRealm.setDefaultRealmPath("/Users/name/Data.realm")
    // var realm: Realm!
    // realm = try! Realm()

    // filter the Database with Predicate
    let objects = realm.objects(Teacher).filter("!!! Need Help !!!", subject)
    // How can I filter the Database? I want to get all the Teachers for that subject

    // Make an Array of Objects
    let objectsArray = objects.toArray(Teacher) as [Teacher]

    // Return
    return ???
}

// This is the toArray extension.
// You may need it to use the snippet above
extension Results {
    func toArray<T>(ofType: T.Type) -> [T] {
        var array = [T]()
        for var i = 0; i < count; i++ {
            if let result = self[i] as? T {
                array.append(result)
            }
        }
        return array
    }
}

So the problem is that I don't know how to filter the Database.

Can someone help me please?

like image 271
Michael_mhr Avatar asked Feb 08 '23 20:02

Michael_mhr


1 Answers

To filter objects that have relations with specific values, or in your case, teachers that have subjects with a specific name, you could use this predicate for a case-insensitive search:

NSPredicate(format: "ANY subjects.name ==[c] %@", subjectName)

and just plug that into the filter function. Since you want to return only the teacher names, you won't need to create any extensions as suggested, but rather use the native swift map method:

func getAllTeacherNamesForSubject(subjectName: String) -> [String] {
    let realm = openRealmDatabase
    let predicate = NSPredicate(format: "ANY subjects.name ==[c] %@", subjectName)

    return realm.objects(Teacher).filter(predicate).map { $0.name }
}

For reference, you can find a great cheatsheet on Realm's website describing the complete list of supported predicate syntax.

like image 147
uɥƃnɐʌuop Avatar answered Feb 22 '23 03:02

uɥƃnɐʌuop