我刚才在swift中尝试过这个,它似乎对我有用。
var sectionsExcludingEmpty: [SurveyAnswerSection] {
let fetchRequest: NSFetchRequest<SurveyAnswerSection> = NSFetchRequest.init(entityName: "SurveyAnswerSection")
fetchRequest.predicate = NSPredicate.init(format: "surveyAnswer == %@ AND hidden == FALSE", self)
fetchRequest.sortDescriptors = [ NSSortDescriptor(key: "surveyAnswer", ascending: true) ]
if let moc = self.managedObjectContext {
do {
let results = try moc.fetch(fetchRequest)
return results
} catch {
fatalError("Could not get sectionsExcludingEmpty: \(error)")
}
} else {
fatalError("Unable to get own managed object context")
}
}
当我错过下线时,fetchRequest.sortDescriptors = [ NSSortDescriptor(key: "surveyAnswer", ascending: true) ]
它看似随机排序,但添加了行后,它按预期排序。
在我的情况下,SurveyAnswerSection 与 SurveyAnswer 具有一对多的关系。