Sorting NSFetchedResultsController by NULL NSDates

Brian Weinreich

I have a tableview that loops through an array of data. The data is a set of contacts that may have a reminder time attached to them. For example:

  • Jessica
  • John
  • Bill
  • Katrina (February 9th)
  • Brian (February 11th)

Right now, it sorts the tableview via the core-data attribute reminderDate in ascending manner. It works semi-correctly. The only catch is I'd like for the items that have a NULL reminderDate to be thrown to the end of the NSFetchedResultsController instead of at the beginning.

Ideally, it'd look like this:

  • Katrina (February 9th)
  • Brian (February 11th)
  • Jessica
  • John
  • Bill

I can't use a comparative NSSortDescriptor as it's not supported by NSFetchedResultsController. Also, I'd rather not perform a sorting after I get results from the NSFetchedResultsController but rather before, when I make the query.

Here is the current code I use:

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"User"];
NSSortDescriptor *sortByDate = [NSSortDescriptor sortDescriptorWithKey:@"reminderDate" ascending:YES];

[fetchRequest setSortDescriptors:@[sortByDate]];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                    managedObjectContext:context
                                                                      sectionNameKeyPath:nil
                                                                               cacheName:nil];

I believe I should be adding another sortDescriptor, but haven't gotten anything to work properly.

Brian Weinreich

I ended up doing what they mentioned here: Using NSSortDescriptor to keep blank values down the list

I made a BOOL value that indicates whether or not the user has reminder set. So, I sort by presence of a reminder, and then by date.

NSSortDescriptor *sortByDate = [NSSortDescriptor sortDescriptorWithKey:@"reminderDate" ascending:YES];
NSSortDescriptor *sortByHasReminder = [NSSortDescriptor sortDescriptorWithKey:@"hasReminder" ascending:NO];

It works well. As a database enthusiast, I hate having unnecessary fields, but it's the best I can do with NSSFetchedResultsController.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related