How to sort EKReminders by due date

When I was developing the Forgot app, I stumbled upon a problem which I could not easily solve: I wanted to sort the reminders I fetched using EventKit, based on their due date. Obviously, I headed to the Apple docs for answers but had very little luck there. What next? Stackoverflow! – could not find anything nor did I get any helpful answers. So I came up with my own solution. Here is the code I used, it’s fairly straight forward:



Basically I am using the sortUsingComparator method of NSArray to sort my reminders. This method takes a block with two objects and expects an NSComparisonResult in return. Our job is to compare the passed in objects (can be any type thus the id) and return an NSComparisonResult based on our comparisons.

What is an NSComparisonResult?

Well, it’s an enum and has three values:




All I had to do now is call the compare method of NSDate which returns an NSComparisonResult.

Tip: Don’t forget to call sortReminders(or whatever you call your method) every time the reminders array changed.  The best way to do this is to register an observer for an EKEventStoreChangedNotification. This way your app will even know about updates made to the Event Store from outside of your app. Here is a code snippet to make your life easier:



Stay tuned for more tips!

Leave a Reply

Your email address will not be published. Required fields are marked *