Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Max Date from NSArray, KVC

I've got an array of NSDates and I'd like to grab the largest NSDate from the array. While i could always sort them and grab the first/last, is there a way to do this with KeyValueCoding or some other quick one liner kind of way? I know that I could use something like valueForKeyPath@"@max.date" if the objects had a date property, but what if the objects are dates themselves??

thanks

like image 389
Sean Danzeiser Avatar asked Dec 08 '22 17:12

Sean Danzeiser


1 Answers

You can use,

NSDate *maxDate = [dateArray valueForKeyPath:@"@max.self"];

This will give you the largest date from array. You dont have to sort the array before doing this.

From the documentation,

The @max operator compares the values of the property specified by the key path to the right of the operator and returns the maximum value found. The maximum value is determined using the compare: method of the objects at the specified key path. The compared property objects must support comparison with each other. If the value of the right side of the key path is nil, it is ignored.

Note that @max will do compare: and then will find out the max value.

like image 92
iDev Avatar answered Dec 11 '22 07:12

iDev