Custom Selector For NSSortDescriptor and NSFetchedResultsController

后端 未结 2 785
被撕碎了的回忆
被撕碎了的回忆 2021-01-05 17:10

I am running into a bit of trouble and I was wondering if someone could provide some guidance.

I am attempting to create section headers with the following order: [\

2条回答
  •  悲&欢浪女
    2021-01-05 17:44

    According to the documentation custom sort doesn't work with SQLite persistent store:

    The SQL store, on the other hand, compiles the predicate and sort descriptors to SQL and evaluates the result in the database itself. This is done primarily for performance, but it means that evaluation happens in a non-Cocoa environment, and so sort descriptors (or predicates) that rely on Cocoa cannot work. The supported sort selectors are compare: and caseInsensitiveCompare:, localizedCompare:, localizedCaseInsensitiveCompare:, and localizedStandardCompare: (the latter is Finder-like sorting, and what most people should use most of the time). In addition you cannot sort on transient properties using the SQLite store.

    So it seems you can't simply force NSFetchedResultsController to display sections in other than alphabetical order.

    But you can use a workaround. Add additional, persistent attribute of integer type to your entity (let's call it sectionOrder). Set its value according to the states property (so it will be 0 for "Push", 1 for "Busy" etc.) You can do that in awakeFromInsert method, for example.

    Then use @"sectionOrder" as both sectionNameKeyPath and the keypath in sort descriptor. You can set section titles to be "Push", "Busy" etc. using this UITableViewDataSource method:

    - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
        id  sectionInfo = [[self.controller sections] objectAtIndex:section];
        return [sectionInfo.objects.firstObject name];
    }
    

    Credits to this excellent answer.

提交回复
热议问题