I’m using Realm in a Swift project to store my data. I want to use the Realm Swift Query API to query object attributes contained in a List.
My (simplified) objects look like:
open class QuestionModel: Object {
@objc dynamic var uuid: String!
override public static func primaryKey() -> String? {
return "uuid"
}
// attributes about the media for this question are wrapped up in a MediaModel object
@objc dynamic var media: MediaModel?
}
open class MediaModel: Object {
// A question can have up to two ImageModels
open var images = List<ImageModel>()
// there are other properties and requirements that justify this Object being here....
}
open class ImageModel: Object {
// The filename on disk to use to create a UIImage
@objc dynamic var filename: String? = nil
// an description of the image
@objc dynamic var altDescription: String? = nil
}
In some circumstances I want to only get QuestionModels where the first ImageModel.filename != “”
Here’s what I’ve tried:
res = realm?.objects(QuestionModel.self)
and I want to further filter the QuestionModels based on certain criteria
Using NSPredicate and Subquery seems to work, though I don’t think it understands which image.name is blank, it just gives me all questions where one of the image.filenames is filled in
res = res.filter("SUBQUERY(media.images, $image, $image.name != '').@count > 0")
However, I really want to move to the new Realm Swift Query API if possible.
res = res.where {
$0.media.images.name != ""
}
NSException * “Key paths that include a collection property must use aggregate operations”
res = res.where {
($0.media.images.name != "").count > 0
}
NSException * “Subqueries must contain a keypath starting with a collection.”
I’m very confused. I can’t seem to find an example online which makes me wonder if this is possible.
Any thought appreciated