我有一个类似this one的问题,但有一点点扭曲。
我想知道当核心数据模型如下所示时,如何在获取请求中返回特定属性(在这种情况下为“#39;权重”):
客户< - >>评估('评估'具有权重属性)
这是我的客户课程:
@objc(Client)
class Client: NSManagedObject {
@NSManaged var name: String
@NSManaged var assessment: NSSet
}
我的评估课:
@objc(Assessment)
class Assessment: NSManagedObject {
@NSManaged var weight: Int16
@NSManaged var nsDateOfAssessment: NSDate
@NSManaged var client: Client
}
这是我的获取请求,因为我有它。我现在理解我的权重'数组正在填充托管对象,但我需要的是填充“权重”的整数。属性,并按我的日期排序  nsDateOfAssessment'如代码的评论中所述。然后我依次使用该数组填充图表。
var client: Client! = nil
var weights = []
func weightFetchRequest() -> NSFetchRequest {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let managedContext = appDelegate.managedObjectContext!
let fetchRequest = NSFetchRequest(entityName: "Assessment")
var error: NSError?
//Something for getting only 'weight' attribute of assessment
//Something for sorting 'weights' array by the date attribute 'nsDateOfAssessment' of 'Assessment'
let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as [NSManagedObject]?
if let results = fetchedResults {
weights = results
} else {
println("Could not fetch \(error), \(error!.userInfo)")
}
println(weights)
return fetchRequest
}
如果有更简单的方法可以做任何输入或指令,我将非常感激。
答案 0 :(得分:2)
您可以通过在NSFetchRequest上设置sortDescriptor来进行排序。传递真或假,具体取决于您是希望结果是放弃还是降低。
var fetchRequest = NSFetchRequest(entityName: "Assessment")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "nsDateOfAssessment", ascending: false)]
然后,您可以使用高阶函数将结果映射到仅获取所需的权重属性
let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as [Assessment]?
注意我是如何将它设置为子类NSManagedObject的数组
if let assessments = fetchedResults {
let weights = assessments.map { assessment in assessment.weight }
}