How to sort NSArray of objects based on one attribute

人盡茶涼 提交于 2019-12-17 10:56:31

问题


I am trying to sort an array of managed objects alphabetically. The attribue that they need to be sorted by is the name of the object (NSString) with is one of the managed attributes. Currently I am putting all of the names in an array of strings and then using sortedNameArray = [sortedNameArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; and then enumerating them back into an array with the objects. This falls apart when two names are the same so I really need to be able to sort by one attribute. How should I go about doing this?


回答1:


Use NSSortDescriptor. Just search the documentation on it and there some very simple examples you can copy right over. Here is a simplified example:

NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc] initWithKey:@"MyStringVariableName" ascending:YES];
NSArray *descriptors = [NSArray arrayWithObject:valueDescriptor]; 
NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:descriptors]; 

And just like that you have a sorted array.




回答2:


You can do this by using NSSortDescriptor,

eg.

`NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc]initWithKey:@"distance" ascending:YES];`

// Here I am sorting on behalf of distance. You should write your own key.

NSArray * descriptors = [NSArray arrayWithObject:valueDescriptor];
NSArray *sortedArray=[yourArray sortedArrayUsingDescriptors:descriptors];`


来源:https://stackoverflow.com/questions/6256046/how-to-sort-nsarray-of-objects-based-on-one-attribute

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