【问题标题】:How to sort array of CoreData objects by integer attributes?如何按整数属性对 CoreData 对象数组进行排序?
【发布时间】:2012-11-19 23:33:18
【问题描述】:

我有一个 CoreData 对象数组,每个对象是 Person,每个 Person 都有一个 age 属性,它的类型是 Integer32。

我的数组充满了Person 对象。我想按他们的age 属性对我的数组进行排序。

我该怎么做?

【问题讨论】:

    标签: iphone objective-c sorting nsarray


    【解决方案1】:

    应该很简单:

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

    无论您在创建 NSManagedObject 子类时是否选择“对原始数据类型使用标量属性”(如果您决定创建它们),这都会起作用

    【讨论】:

      【解决方案2】:

      说“人”是您要排序的 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;
      }
      

      【讨论】:

      • 'else' 在这里是多余的,因为您在每个肯定的情况下都会返回。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 2011-09-06
      • 2012-02-20
      • 2010-11-02
      相关资源
      最近更新 更多