如何使用特定的托管对象来构造排序描述符?

发布于 2024-12-16 17:05:01 字数 427 浏览 0 评论 0原文

实体 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

断念 2024-12-23 17:05:01

正如您已经意识到的那样,您无法通过一对多进行排序。执行此操作的“最干净”方法是实现您自己的排序,您可以在获取图书实体后在内存中执行该排序。一旦它进入内存,您就可以通过一种方便的方法来排序,而不仅仅是数据。

例如,您的 Book 子类上可以有一个名为 -localTitle 的方法,它从正确的描述中返回适当的标题。从那里您可以对 localTitle 进行排序。

基本上:

  1. 您将创建一个 NSFetchedResultsController 来跟踪更改。
  2. 当检测到更改时,您重新创建一个按 localTitle 排序的数组。
  3. 您告诉您的表视图重新加载。
  4. 您的表视图从数组而不是 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 on localTitle.

Basically:

  1. You would create a NSFetchedResultsController to track changes.
  2. When a change is detected you re-create an array that is sorted by the localTitle
  3. You tell your table view to reload
  4. Your table view feeds off the array and NOT the NSFetchedResultsController.

You could do away with the NSFetchedResultsController but that gets a little more complicated.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文