Reputation: 17169
I have an array of CoreData objects, each object is Person
and each Person
has an age
attribute which is of type Integer32.
My array is filled with Person
objects. I want to sort my array by their age
attribute.
How can I do this?
Upvotes: 4
Views: 2183
Reputation: 38728
It should be as simple as:
NSArray *sortDescriptors = @[
[NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES]
];
NSArray *sortedPeople = [people sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"%@", sortedPeople);
This will work regardless of whether you do or do not choose to "Use scalar properties for primitive data types" when creating your NSManagedObject
subclass (if you decide to even create them)
Upvotes: 8
Reputation: 2650
Say "people" is your array of Person objects you want sorted...
NSArray *sortedPeople = [people sortedArrayUsingComparator:^NSComparisonResult(Person *p1, Person *p2) {
if (p1.age > p2.age) return NSOrderedDescending;
else if (p1.age < p2.age) return NSOrderedAscending;
else return NSOrderedSame;
}
Upvotes: 0