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

时间:2015-01-18 18:46:49

标签: swift core-data nssortdescriptor

我想对NSSet内的获取请求返回的对象进行排序或过滤(来自多对多关系)。此处routineSplitsRelNSSet RoutineSplits,应该在" displayOrder"中返回。应用sortdescriptor1会返回错误说明:

  

' to-many key不允许在这里'

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

}

FetchRequest:

    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]

1 个答案:

答案 0 :(得分:3)

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

将其“转换”为Array

所以它会是那样的

fetchResults.allObjects.sort({ $0.displayOrder.integerValue > $1.displayOrder.integerValue })