如何在一对多关系的 NSSet 上应用 NSSortdiscriptor 或 NSPredicate

How to apply NSSortdiscriptor or NSPredicate on a NSSet of a to-many relationship

我想对 NSSet(从一对多关系)中的提取请求返回的对象进行排序或过滤。这里 routineSplitsRelRoutineSplitsNSSet,应该在 "displayOrder" 中返回。应用 sortdescriptor1 returns 一个错误说:

'to-many key not allowed here'

class Routines: NSManagedObject {

@NSManaged var id: NSNumber
@NSManaged var isdeleted: NSNumber
@NSManaged var name: String
@NSManaged var repetitions: String
@NSManaged var uid: String
@NSManaged var updatedat: NSDate
@NSManaged var displayOrder: NSNumber
@NSManaged var trainingdayRel: NSSet
@NSManaged var exercisesRel: NSSet
@NSManaged var routineSplitsRel: NSSet

}

class RoutineSplits: NSManagedObject {

@NSManaged var id: NSNumber
@NSManaged var uid: String
@NSManaged var displayOrder: NSNumber
@NSManaged var isdeleted: NSNumber
@NSManaged var name: String
@NSManaged var routinesRel: myTP.Routines

}

获取请求:

    let fetchRequest = NSFetchRequest(entityName: "Routines")
    let sortDescriptor = NSSortDescriptor(key: "displayOrder", ascending: true)
    let sortDescriptor1 = NSSortDescriptor(key: "routineSplitsRel.displayOrder", ascending: true)
    fetchRequest.predicate = NSPredicate(format: "isdeleted == %@",NSNumber(bool: false))
    fetchRequest.sortDescriptors = [sortDescriptor,sortDescriptor1]

您不能直接对一对多关系进行排序。 您需要获取它们,然后才能对它们进行排序。 当你得到你的 NSSet 时,你可以使用 mySet.allObjects()

"convert" 它到 Array

所以会是这样的

fetchResults.allObjects.sort({ [=10=].displayOrder.integerValue > .displayOrder.integerValue })