问题
I have a realm object Song with dynamic var title = "". I've written a computed property, sortedName that sorts out any pesky prefixes like "The " or parentheses and punctuation. I want my RealmSearchViewController to use sortedName as its sortProperty but this is throwing the error: "Property 'sortedName' not found in object of type 'Song'"
I get the same error when using sortedName in predicates (such as if results.objects(with: NSPredicate(format: "sortedName BEGINSWITH %@", key)).count > 0)
I get this same behavior whether sortedName is written in my Song class or whether it's written in extension Object (which is what I want to do so I can use sortedName in my Artist and Genre classes as well).
The property does exist, and it works on its own: When I set cell.detailTextLabel?.text = song.sortedName (after removing references that cause the above errors) it displays correctly.
Is there a way to make this work?
回答1:
Unfortunately, at the moment, querying for Realm objects can only be done with non-computed, Realm-persisted properties.
There's plans within Realm to add a feature where it's possible to manually sort Realm objects with a block, but there's no time frame for that yet.
For the time being, you'd be better off copying the objects in Results to a Swift array and sort them in there. It's a bit of a performance hit (As it means having to access all of the Realm objects up front), but it will let you perform custom sorting on them.
Alternatively. You could 'cache' the sorted ordering by adding another type of Realm Object to your database that maintains a List object that controls the ordering of those objects.
来源:https://stackoverflow.com/questions/43834998/computed-property-as-in-predicates-and-as-sortproperty-in-realmsearchviewcontro