Filling an array with core data attributes

左心房为你撑大大i 提交于 2019-12-13 18:26:09

问题


I'm trying to fill my array.

var weights = [] 

with attributes from an NSManaged object. My core data relationship is like follows Client<-->>Assessment. I have a 'weight' attribute within assessment and I would like to fill my array with these values which are strings. My variable:

var client: Client! = nil 

successfully retrieves the specific client that I have selected, but I do not know how to fill my array with the values of that particular client's assessment attribute called 'weight'. I've only gotten as far as...

client.assessment.count

which successfully shows me the number of assessments the client has, but how to I access the weight attribute of each of those assessments for my array?

My managed object classes for Client and Assessment are as follows:

Client.swift

import Foundation
import CoreData

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

Assessment.swift

import Foundation
import CoreData

@objc(Assessment)
class Assessment: NSManagedObject {
    @NSManaged var weight: String
    @NSManaged var client: Client
}

Can anyone help me know how to do this?

UPDATE: Screenshot of the error I get with @Wain 's answer.


回答1:


You can use KVC to get the weights in a set:

var weights: NSSet! = client.assessment.valueForKey("weight")

And then you can extract an array from that by sorting or just requesting all objects.



来源:https://stackoverflow.com/questions/29085140/filling-an-array-with-core-data-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!