Custom NSSortDescriptor for NSFetchedResultsController

I have a custom "sort" that I currently perform on a set of data. I now need to perform this sort on the fetchedObjects in the NSFetchedResultsController. All of our table data works hand in hand with core data fetched results so replacing the data source with a generic array has been problematic.

Since NSFetchedResultsController can take NSSortDescriptors it seems like that is the best route. The problem is I don't know how to convert this sort algorithm into an custom comparator.

How do I convert this into a custom comparator (if possible)? (if not how do I get the desired sorted result while using NSFetchedResultsController). In essence the field 'priority' can be either 'high' 'normal' or 'low' and the list needs to be sorted in that order.

+(NSArray*)sortActionItemsByPriority:(NSArray*)listOfActionitemsToSort
{
    NSMutableArray *sortedArray = [[NSMutableArray alloc]initWithCapacity:listOfActionitemsToSort.count];
    NSMutableArray *highArray = [[NSMutableArray alloc]init];
    NSMutableArray *normalArray = [[NSMutableArray alloc]init];
    NSMutableArray *lowArray = [[NSMutableArray alloc]init];

for (int x = 0; x < listOfActionitemsToSort.count; x++)
{
    ActionItem *item = [listOfActionitemsToSort objectAtIndex:x];

    if ([item.priority caseInsensitiveCompare:@"high"] == NSOrderedSame)
        [highArray addObject:item];
    else if ([item.priority caseInsensitiveCompare:@"normal"] == NSOrderedSame)
        [normalArray addObject:item];
    else
        [lowArray addObject:item];
}

[sortedArray addObjectsFromArray:highArray];
[sortedArray addObjectsFromArray:normalArray];
[sortedArray addObjectsFromArray:lowArray];

return sortedArray;
}

UPDATE Tried using a NSComparisonResult block but NSFetchedResultsController does not allow that

Also tried using a transient core data attribute and then calculating a field that I could sort. But the sort takes place before the field is calculated so that didn't work.

I tried setting sections for each priority type - which worked. But it wasn't displaying in the right order and apparently you cannot order sections with core data.

Any other thoughts?


这个怎么样?

NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"priority" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
        if ([obj1 isEqualToString:obj2]) {
            return NSOrderedSame;
        } else if ([obj1 isEqualToString:@"high"] || [obj2 isEqualToString:@"low"]) {
            return NSOrderedAscending;
        } else if ([obj2 isEqualToString:@"high"] || [obj1 isEqualToString:@"low"]) {
            return NSOrderedDescending;
        }
        return NSOrderedSame;
    }];
链接地址: http://www.djcxy.com/p/6148.html

上一篇: 在NSFetchedResultsController中排序部分问题

下一篇: 自定义NSSortDescriptor NSFetchedResultsController