如何使用特定的托管对象来构造排序描述符?
实体 B(Book)与实体 D(Description)具有一对多关系。这个想法是一本书对不同的语言有不同的描述。
我想根据给定语言 (D.languageID) 的书名 (D.title) 对书籍进行排序
如果 B 与 D 具有一对一的关系,我会这样做:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"d.title" ascending:YES];
当然,你可能会说,模型并不妨碍一本书有许多具有相同 languageID 的描述。但在这种情况下,任何(例如第一个)描述对我来说都可以。或者我可以先获取所需的Description对象,但是如何在排序中使用它?
难道是我的模型不对?在这种情况下最好的解决方案是什么?
Entity B (Book) has a one-to-many relationship with the entity D (Description). The idea is that a book has different descriptions for different languages.
I want to sort books based on their titles (D.title) for a given language (D.languageID)
If B had one-to-one relationship to D, I would do something like:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"d.title" ascending:YES];
Of course, you may say, the model does not prevent a book from having many descriptions with the same languageID. But in this case any (e.g. the first) description would be ok for me. Or I can fetch the needed Description object before, but then how to use it in the sorting?
Is my model wrong? What's the best solution in this case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如您已经意识到的那样,您无法通过一对多进行排序。执行此操作的“最干净”方法是实现您自己的排序,您可以在获取图书实体后在内存中执行该排序。一旦它进入内存,您就可以通过一种方便的方法来排序,而不仅仅是数据。
例如,您的 Book 子类上可以有一个名为
-localTitle
的方法,它从正确的描述中返回适当的标题。从那里您可以对localTitle
进行排序。基本上:
localTitle
排序的数组。NSFetchedResultsController
获取数据。您可以取消 NSFetchedResultsController ,但这会变得更复杂一些。
You can't sort via a one to many as you have already realized. The "cleanest" way to do this would be to implement your own sort that you can perform in memory after the book entities have been fetched. Once it is in memory you can sort via a convenience method instead of just data.
For example, you could have a method on your Book subclass that is called
-localTitle
which returns the appropriate title from the right description. From there you could sort onlocalTitle
.Basically:
NSFetchedResultsController
to track changes.localTitle
NSFetchedResultsController
.You could do away with the
NSFetchedResultsController
but that gets a little more complicated.