Sort NSArray of custom objects by their NSDate properties

后端 未结 5 1273
执笔经年
执笔经年 2020-11-30 06:20

I am attempting to sort an NSArray that is populated with custom objects. Each object has a property startDateTime that is of type NSDate.

The followin

5条回答
  •  青春惊慌失措
    2020-11-30 06:30

    Ok, I know this is a little late, but this is how I would do it:

    NSArray *sortedEventArray = [events sortedArrayUsingComparator:^NSComparisonResult(Event *event1, Event *event2) {
        return [event1.startDateTime compare:event2.startDateTime];
    }];
    

    Obviously, replace Event with the class of your custom object. The advantage of this approach is that you are protected against future refactoring. If you were to refactor and rename the startDateTime property to something else, Xcode probably would not change the string you're passing into the sort descriptor. Suddenly, your sorting code would break/do nothing.

提交回复
热议问题