Sorting an array of CoreData objects by Integer attribute?

I have an array of CoreData objects, each Person object, and each Person has an age attribute that is of type Integer32.

My array is populated with Person objects. I want to sort an array by their age attribute.

How can i do this?

Any help is much appreciated, thanks.

+4
source share
2 answers

It should be simple:

 NSArray *sortDescriptors = @[ [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES] ]; NSArray *sortedPeople = [people sortedArrayUsingDescriptors:sortDescriptors]; NSLog(@"%@", sortedPeople); 

This will work regardless of whether or not you use β€œUse scalar properties for primitive data types” when creating your NSManagedObject subclass (if you decide to even create them)

+8
source

Say "people" - this is your array of Person objects that you want to sort ...

 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; } 
0
source

Source: https://habr.com/ru/post/1447099/


All Articles