从一对多关系核心数据中检索数据

时间:2015-11-23 06:25:00

标签: ios swift core-data one-to-many

我需要检索多对多关系中每个属性的值。我加载它的代码是

func loadData() {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext

    let fetchRequest = NSFetchRequest(entityName: "Company")

    do {
        //Get the results
        let results = try managedContext.executeFetchRequest(fetchRequest)
        //Load the results in the people array
        people = results as! [NSManagedObject]
        for i in 0..<people.count {
            let data = people[i]
            let variableToPrint = data.valueForKey("employee")
            print(variableToPrint)
        }
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }
}

如果我这样做,它会返回:

  

可选(关系&#39;员工&#39;托管对象的错误   (0x7f93f363dd80)(实体:公司;   id:0xd000000000080000    ;数据:   {       employee =&#34;&#34 ;;       name = Apple; }))

我保存到核心数据的代码是

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

let managedContext = appDelegate.managedObjectContext

let companyEntity = NSEntityDescription.entityForName("Company", inManagedObjectContext: managedContext)
let company = NSManagedObject(entity: companyEntity!, insertIntoManagedObjectContext: managedContext)
    company.setValue("Apple", forKey: "name")

//Add employees
let employeeEntity = NSEntityDescription.entityForName("Employees", inManagedObjectContext: managedContext)

let person = NSManagedObject(entity: employeeEntity!, insertIntoManagedObjectContext: managedContext)
for i in 0..<employeeNameArray.count {
        let name = employeeNameArray[i]
        let when = dateJoinedArray[i]
        let number = employeeNumberArray[i]

        person.setValue(name, forKey: "employeeName")
        person.setValue(number, forKey: "employeeNumber")
        person.setValue(when, forKey: "dateHired")
        company.setValue(NSSet(object: person), forKey: "employee")
}

//Employee info to company        
company.setValue(NSSet(object: person), forKey: "employee")

do {
    try managedContext.save()
    //people.append(person)
} catch let error as NSError {
    print("Could not save \(error), \(error.userInfo)")
}

我的核心数据设置有2个实体。一个叫公司,一个叫雇员。 公司有一个名称属性,以及一个目标为Employees的员工关系,并且有很多。

在员工中,我有`dateHired,employeeName和employeeNumber属性,在关系中,我与目标公司有一个名为company的关系,并且属于一种类型。

我需要能够在公司属性的同时加载所有Employees属性,因为它们绑在一起。

0 个答案:

没有答案