How to sort NSArray of objects based on one attribute
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.
Comments
-
Jackelope11 about 4 years
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?-
retrodrone almost 13 yearsHave a look at this question. I think it will help you.
-
Jackelope11 almost 13 yearsIt is helpful but so complex - I have a hard time understanding it, thanks though.
-
Meet Doshi over 8 yearsTry this.. stackoverflow.com/a/34610703/3908884
-
-
Jackelope11 almost 13 yearsThank you so much, this will save me hours and that means a lot when the deadline is in a week and a half.
-
Dancreek almost 13 yearsNo problem. Glad I could help.
-
Mike Gledhill almost 8 yearsYup, thank you... Sometimes, a decent example as the only way to cope with this over-bloated Objective-C coding.