arrays - NSSortDescriptor using NSDate attribute of Entity (Swift) -
i have question similar this one little twist.
i wondering how return specific attribute ('weight' in case) in fetch request when core data model follows:
client <-->> assessment ('assessment' has weight attribute)
here's client class:
@objc(client) class client: nsmanagedobject { @nsmanaged var name: string @nsmanaged var assessment: nsset }
and assessment class:
@objc(assessment) class assessment: nsmanagedobject { @nsmanaged var weight: int16 @nsmanaged var nsdateofassessment: nsdate @nsmanaged var client: client }
and here's fetch request have it. understand right 'weights' array being filled managed objects, need filled ints of 'weight' attribute, , sorted date 'nsdateofassessment' described in comments of code. in turn using array fill graph.
var client: client! = nil var weights = [] func weightfetchrequest() -> nsfetchrequest { let appdelegate = uiapplication.sharedapplication().delegate appdelegate let managedcontext = appdelegate.managedobjectcontext! let fetchrequest = nsfetchrequest(entityname: "assessment") var error: nserror? //something getting 'weight' attribute of assessment //something sorting 'weights' array date attribute 'nsdateofassessment' of 'assessment' let fetchedresults = managedcontext.executefetchrequest(fetchrequest, error: &error) [nsmanagedobject]? if let results = fetchedresults { weights = results } else { println("could not fetch \(error), \(error!.userinfo)") } println(weights) return fetchrequest }
would appreciate input or instruction if there easier way this.
you can sort setting sortdescriptor on nsfetchrequest. pass true or false depending on if want results acending or descending.
var fetchrequest = nsfetchrequest(entityname: "assessment") fetchrequest.sortdescriptors = [nssortdescriptor(key: "nsdateofassessment", ascending: false)]
you use high order function map results weight attribute want
let fetchedresults = managedcontext.executefetchrequest(fetchrequest, error: &error) [assessment]?
notice how i'm setting array of subclassed nsmanagedobject
if let assessments = fetchedresults { let weights = assessments.map { assessment in assessment.weight } }
Comments
Post a Comment