How to use NSComparator?

北战南征 提交于 2019-12-04 18:55:16

问题


I would like to know if the below question is possible using NSComparator or not?

I have two arrays; both hold data models. I have a property named rank in the data model. Now I want to compare both arrays and want to know if one of them holds higher ranked data models. If Yes I would like to get NSComparisonResult = NSOrderedAscending.

By the way I'm using another approach here: is "total of each data Model's rank in array and if the total is greater than second array's data Model's total rank."


回答1:


Yes, it would look something like this:

NSArray *someArray = /* however you get an array */    
NSArray *sortedArray = [someArray sortedArrayUsingComparator:^(id obj1, id obj2) {
  NSNumber *rank1 = [obj1 valueForKeyPath:@"@sum.rank"];
  NSNumber *rank2 = [obj2 valueForKeyPath:@"@sum.rank"];
  return (NSComparisonResult)[rank1 compare:rank2];
}];

(updated to show actually using the comparator)



来源:https://stackoverflow.com/questions/5064033/how-to-use-nscomparator

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