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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With