Lazy sorting

Yesterday I mentioned an issue I can across when sorting date records. Some of my date records could validly have a nil value in the date field (these are the “end” records for ongoing events). The problem was that Core Data was sorting these nil records to the wrong part of the list. When sorting descending, they should be at the top of the list, but they were at the bottom.

There are a ton of ways to tackle a problem like this: custom sort descriptor, sort by a derived value, omit the nil values, fetch the nil records in a different section, etc. I didn’t do any of these.

Instead I cheated. I added a new Boolean field called isOngoing and set it to false for all new records. When a user marks a record as “Ongoing” I toggle this to true. Then I modified my sorting to sort by this field, then the date field. This has an added bonus of letting me easily group these two types (true and false) into discrete sections in list view. I may even add a control to let the user hide the ongoing records and all I have to do is hide the section or drop in a predicate to filter out the true values.

This is a lazy way of solving this, but I’m happy with the results.