objective-ceventkit

How can I sort an array of EKEvent by date?


I have an array that stores events fetched via a predicate; I want to sort them by date. I read that I have to "call sortedArrayUsingSelector: on the array, providing the selector for the compareStartDateWithEvent: method', but I don't know how to use it exactly. Could someone provide me an example?

Here's my array: NSArray *events = [store eventsMatchingPredicate:predicate] Thanks!


Solution

  • Once you have your array, consider:

    NSArray *sortedArray = [events sortedArrayUsingComparator:^NSComparisonResult(EKEvent *event1, EKEvent *event2) {
        return [event1.startDate compare:event2.startDate];
    }];
    

    This would sort the events by start date, using the built-in NSDate - compare function.

    The - sortedArrayUsingComparator method takes an NSComparator block, which is defined as:

    typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);
    

    You can basically think of it as a block (a lambda-function) that takes two arguments, and you return an NSComparisonResult member that explains what the ordering of the two given objects are. The type of the object depends on what you shoved into your array, in this case EKEvents. How you sort them is up to you; read up on NSComparator for more info and the rules. NSArray will call your block multiple times, presenting two items each time, until the array is sorted.

    Now, lucky you, EKEvent exposes a selector which knows how to compare to EKEvents. NSArray has another method, sortedArrayUsingSelector: that you can use, and just tell it to use the comparison selector that EKEvent exposes:

    NSArray *sortedArray = [events sortedArrayUsingSelector:@selector(compareStartDateWithEvent:)];
    

    Now NSArray will call - compareStartDateWithEvent: each time it wants to compare two items. If that is the ordering you want, you can use it. Otherwise, use the comparator method above.