Ios 从一对多关系核心数据检索数据
我需要检索多对多关系中每个属性的值。我加载它的代码是Ios 从一对多关系核心数据检索数据,ios,swift,core-data,one-to-many,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")
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)")
}
}
func loadData(){
让appDelegate=UIApplication.sharedApplication()。委托为!appDelegate
让managedContext=appDelegate.managedObjectContext
let fetchRequest=NSFetchRequest(entityName:“公司”)
做{
//得到结果
让结果=尝试managedContext.executeFetchRequest(fetchRequest)
//将结果加载到人员数组中
人员=结果为![NSManagedObject]
对于0中的i..您可以简单地使用company.employees,这是由核心数据本身创建的NSSet,无需对公司和员工执行提取请求。您面临的问题是什么?是否返回了任何记录?而且您收到的消息不是错误。请检查此链接。不清楚您的实际问题是什么…不要担心关注“关系‘雇员’错误”-这是完全正常的-请参阅。@someonecalledphilippe要获得一个集合,其中包含employee
关系的“name”属性的所有值(例如),只需使用let variableToPrint=data.valueForKeyPath(“employee.name”)
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)")
}