Getting Max Date from NSArray, KVC

喜夏-厌秋 提交于 2019-12-18 17:48:33

问题


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


回答1:


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.




回答2:


Agree with @SeanDanzeiser. To be more specific, here's a ~70 byte one-liner:

// if dateArray is the array of dates ...
NSDate *maxDate = [[dateArray sortedArrayUsingSelector:@selector(compare:)] lastObject];


来源:https://stackoverflow.com/questions/15147617/getting-max-date-from-nsarray-kvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!