Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering Realm objects with Swift

I always get the following error when trying to filter my Realm database using NSPredicate:

Property 'text' is not a link in object of type 'getType'

I want to filter my Realm database to show only the items that have some specific text in them. This is what I've tried:

let realm = try! Realm()
let predicate = NSPredicate(format: "typez.text.filter = 'special'")
let filterThis = realm.objects(Publication).filter(predicate)
print(filterThis)

The relevant portion of my model classes is:

class Publication: Object, Mappable {
    dynamic var id: Int = 0
    var typez = List<getType>()
    dynamic var url: String?
}

class getType: Object, Mappable {
    dynamic var text: String = ""
}
like image 704
SoundShock Avatar asked Apr 25 '16 14:04

SoundShock


People also ask

How do I filter in realm?

To filter data in your realm, you can leverage Realm Database's query engine. The Realm Swift Query API offers an idiomatic way for Swift developers to query data. Use Swift-style syntax to query Realm Database with the benefits of auto-completion and type safety.

Does realm work with SwiftUI?

Realm objects have bindings to SwiftUI controls and, much like toggling the bought property, they already start a realm transaction to write the changes in the database whenever you change those values.

Can we store image in realm?

You can either upload the image to an open-source image uploader, like Imgur, and then download it back to cache it, or you can store the image locally in your Realm database. The latter has the advantage that it does not require Internet connectivity.

What is realm react native?

Realm is a mobile database that runs directly inside phones, tablets or wearables. This project hosts the JavaScript versions of Realm. Currently we support React Native (both iOS & Android), Node. js and Electron (on Windows, MacOS and Linux).


1 Answers

You mentioned that the relevant portions of you model classes look like so:

class Publication: Object, Mappable {
    dynamic var id: Int = 0
    var typez = List<getType>()
    dynamic var url: String?
}

class getType: Object, Mappable {
    dynamic var text: String = ""
}

If I understand you correctly, you want to find Publication instances that have an entry in their typez list with text equal to special. You can express that as:

let realm = try! Realm()
let result = realm.objects(Publication).filter("ANY typez.text = 'special'")
print(result)
like image 133
bdash Avatar answered Sep 18 '22 22:09

bdash