Question

I have an array of custom objects, PNMessage objects. The PNMessage Objects have a property which is another object named PNDate, the PNDate has a property called date, I would like to sort my array by the PNDate's date property.

I think I could probably use sort descriptors but I don't know how to drill down to the property object PNDate and then sort by the PNDate date property.

here is a representation:

myArray - My array PNMessage - Custom objects in my array. PNDate - Property (also an object) of main custom objects. date - THIS IS THE PROPERTY THAT I WANT TO USE FOR SORTING MY ARRAY.

Is this possible?

This is what I tried but I know it's wrong, I can't seem to wrap my head around how to drill down to that property to sort the array:

 NSSortDescriptor *dateDescriptor = [NSSortDescriptor
                                                    sortDescriptorWithKey:@"date"
                                                    ascending:YES];
                NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
                NSArray *sortedEventArray = [self.chatHistory
                                             sortedArrayUsingDescriptors:sortDescriptors];

Any help would be greatly appreciated!

Was it helpful?

Solution

Rather than using sort descriptors, you could use a comparator block.

NSArray *sortedEventArray =
[self.chatHistory sortedArrayUsingComparator:^NSComparisonResult(PNMessage *m1, PNMessage *m2) {
    return [m1.date compare:m2.date];
}];

Note that the PNDate class must have an instance method called -[PNDate compare:] that returns NSComparisonResult for this to work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top