0

I have a question similar to this one but with a little twist.

I am wondering how to return a specific attribute ('weight' in this case) in a fetch request when the core data model is like follows:

Client <-->> Assessment ('Assessment' has a weight attribute)

Here's my Client class:

@objc(Client)
class Client: NSManagedObject {
    @NSManaged var name: String
    @NSManaged var assessment: NSSet
}

And my Assessment class:

@objc(Assessment)
class Assessment: NSManagedObject {

    @NSManaged var weight: Int16
    @NSManaged var nsDateOfAssessment: NSDate
    @NSManaged var client: Client

}

And here's my fetch request as I have it. I understand that right now my 'weights' array is being filled with managed objects, but what I need is for it to be filled with the ints of 'weight' attribute, and sorted by my date 'nsDateOfAssessment' as described in the comments of the code. I am then in turn using that array to fill a graph.

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
    }

Would greatly appreciate any input or instruction if there is an easier way to do this.

Community
  • 1
  • 1
Leighton
  • 6,559
  • 7
  • 21
  • 28
  • Check out documentation of NSFetchRequest, specially sortDescriptors, predicates and propertiesToFetch members. – Abdullah Apr 01 '15 at 13:40

1 Answers1

2

You can sort by setting a sortDescriptor on the NSFetchRequest. Pass true or false depending on if you want the results to be acending or descending.

var fetchRequest = NSFetchRequest(entityName: "Assessment")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "nsDateOfAssessment", ascending: false)]

You could then use a high order function to map the results to only get the weight attribute you want

let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as [Assessment]?

Notice how I'm setting it to be an array of your subclassed NSManagedObject

if let assessments = fetchedResults {
   let weights = assessments.map { assessment in assessment.weight }
}
aahrens
  • 5,522
  • 7
  • 39
  • 63