[英]How to sort array of CoreData objects by integer attributes?
I have an array of CoreData objects, each object is Person
and each Person
has an age
attribute which is of type Integer32. 我有一个CoreData对象数组,每个对象都是
Person
,每个Person
都有一个Integer32类型的age
属性。
My array is filled with Person
objects. 我的数组充满了
Person
对象。 I want to sort my array by their age
attribute. 我想按照他们的
age
属性对数组进行排序。
How can I do this? 我怎样才能做到这一点?
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) 无论您是否在创建
NSManagedObject
子类时选择“使用标量属性作为基本数据类型”(如果您决定创建它们),这都将起作用
Say "people" is your array of Person objects you want sorted... 说“people”是你想要排序的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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.