2015-04-01 53 views
0

我有一個類似於this one的問題,但有點麻煩。使用Entity(Swift)的NSDate屬性的NSSortDescriptor

我想知道如何(在這種情況下,「重量」)返回的特定屬性在當核心數據模型就像是獲取請求如下:

客戶< - >>評估(「評估」有權重屬性)

這裏是我的客戶端類:

@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 

} 

這是我的提取請求,因爲我擁有它。我明白現在我的'權重'數組被充滿了管理對象,但我需要的是它被填充'weight'屬性的整數,並按照我的日期'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

查看NSFetchRequest的文檔,特別是sortDescriptors,predicates和propertiesToFetch成員。 – Abdullah 2015-04-01 13:40:37

回答

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 } 
} 
+0

完美!謝謝! – Leighton 2015-04-01 14:33:01

相關問題