Transient sectionNameKeyPath & NSSortDescriptor NSFetchedResultsController

与世无争的帅哥 提交于 2019-12-03 15:41:18

问题


I have a list of tasks within Core Data. I fetch them into a UITableView using an NSFetchedResultsController.

I need custom sections in a custom order:

  1. OVERDUE
  2. ACTIVE
  3. ONGOING
  4. POSTPONED
  5. COMPLETED

To determine what section a task should go in I use a derived transient attribute calculated on the fly based on other attributes in the relative object.

Unfortunately you cannot pass a derived value as a sort descriptor used by a fetch request. This is because a fetch relies on already having data it is being asked to fetch. Chicken & Egg.

I understand why I can't do it, that doesn't help me solve the problem!

I've tried:

  • Subclassing NSFetchedResultsController to 'customise creation of sections and index titles'. Maybe I'm doing this wrong however this just changes the names and orders of sections, not how many things go in those sections (which is critical).

  • Populating arrays per section and feeding them to the table (clunky, slow yet fully works).

  • Ripping out ongoing & postponed tasks (which works, but isn't ideal). This way I can sort by dueDate and drive the sectionNameKeyPath via the transient values.

Does anyone have any better ideas? There are quite a few questions already just like this one yet none of them come to a neat solution.

Thanks in advance!

Cheers


回答1:


The simplest solution is to add a persistent 'section' attribute (or convert your existing transient attribute). Make it a set of sortable values (which you display at runtime using the names you want). Whenever you update any record, recompute and store the section attribute as well.

I realize this sounds like you're storing redundant information but besides making your logic simpler, it will also be indexable which will speed access.



来源:https://stackoverflow.com/questions/10481860/transient-sectionnamekeypath-nssortdescriptor-nsfetchedresultscontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!