问题描述
我有一个带dynamic var title = ""
的领域对象Song
.我编写了一个计算属性sortedName
,它可以对所有讨厌的前缀(例如"The"或括号和标点符号)进行排序.我希望我的RealmSearchViewController
使用sortedName
作为其sortProperty
,但这会引发错误:"Property 'sortedName' not found in object of type 'Song'"
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'"
在谓词(例如if results.objects(with: NSPredicate(format: "sortedName BEGINSWITH %@", key)).count > 0
)中使用sortedName
时遇到相同的错误
I get the same error when using sortedName
in predicates (such as if results.objects(with: NSPredicate(format: "sortedName BEGINSWITH %@", key)).count > 0
)
无论sortedName
是在我的Song
类中编写还是在extension Object
中编写,我都会得到相同的行为(这是我想要做的,因此我可以在Artist
和Genre
类).
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).
该属性确实存在,并且可以单独工作:当我设置cell.detailTextLabel?.text = song.sortedName
(删除导致上述错误的引用后)时,它会正确显示.
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?
推荐答案
不幸的是,目前,只能使用非计算的,Realm持久的属性来查询Realm对象.
Unfortunately, at the moment, querying for Realm objects can only be done with non-computed, Realm-persisted properties.
Realm计划添加此功能,该功能可以使用封锁,但目前尚无时间表.
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.
暂时最好将Results
中的对象复制到Swift数组中并在其中排序.这对性能有一定的影响(因为这意味着必须先访问所有Realm对象),但是它可以让您对它们执行自定义排序.
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.
或者.您可以通过在数据库中添加另一种Realm Object
来缓存"排序的顺序,该领域维护一个List
对象,该对象控制这些对象的顺序.
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.
这篇关于如谓词中的计算属性,以及RealmSearchViewController中的sortProperty?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!