我有一个 CoreData 对象数组,每个对象都是Person
并且每个对象Person
都有一个age
Integer32 类型的属性。
我的数组充满了Person
对象。我想按他们的age
属性对我的数组进行排序。
我怎样才能做到这一点?
我有一个 CoreData 对象数组,每个对象都是Person
并且每个对象Person
都有一个age
Integer32 类型的属性。
我的数组充满了Person
对象。我想按他们的age
属性对我的数组进行排序。
我怎样才能做到这一点?
它应该很简单:
NSArray *sortDescriptors = @[
[NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES]
];
NSArray *sortedPeople = [people sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"%@", sortedPeople);
无论您在创建NSManagedObject
子类时是否选择“对原始数据类型使用标量属性”(如果您决定创建它们) ,这都将起作用
说“人”是您要排序的 Person 对象数组...
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;
}