swiftxcoderealmrealm-database

Error in Realm invalid property name when I want to filter data, property not found


I get the error *** Terminating app due to uncaught exception 'Invalid property name', reason: 'Property 'read' not found in object of type 'Book'' when I want to filter my data. My structure:

class Book: Object, Codable {
@objc dynamic var author = ""
@objc dynamic var title = ""
@objc dynamic var imageLink = ""
@objc dynamic var category = "Lk"
@objc dynamic var date = Date()

convenience init(withBookDict: [String: Any]) {
    self.init()

    self.author = withBookDict["author"] as? String ?? "No Author"
    self.title = withBookDict["title"] as? String ?? "No Title"
    self.imageLink = withBookDict["imageLink"] as? String ?? "No link"
    self.category = withBookDict["category"] as? String ?? "No category"
 }
}

my code for filtering data is this:

let filteredread = realm.objects(Book.self).filter({ $0.category == "read"})

but I also tried this:

 let filteredread = realm.objects(Book.self).filter("category == 'read'")

also I did update my realm pod since there have been version issues.


Solution

  • There's actually nothing wrong with your code, other than a "typo" - but there's other stuff to consider.

    Fixing the typo

    let filteredread = realm.objects(Book.self).filter({ $0.category == "read"})
    

    should be

    let filteredread = realm.objects(Book.self).filter { $0.category == "read"}
    

    note removing the () from the filter function (which is actually a Swift .filter). This is more for clarity than anything as using swift functions on Realm objects can cause issues.

    That query will first read all of the Book objects, then perform a Swift filter on the results and return LazyFilterSequence<Results> object. What that means is the results are disconnected from Realm and will not auto-update, which is one of the key features of realm.

    If you want to have the Results update, do not use Swift functions; use Realm functions only

    let filteredread = realm.objects(Book.self).filter("category == 'read'")
    

    which returns a Results, which will auto-update as the underlying data changes.

    Note: that function matches what's in your question and is perfectly legitimate code and would not throw any errors.