gpt4 book ai didi

ios - 核心数据一对多关系在创建新关系时被删除

转载 作者:行者123 更新时间:2023-11-29 01:39:31 24 4
gpt4 key购买 nike

我是 Core Data 的新手,在探索它的工作方式时,我发现自己陷入了另一个问题。

我正在从两个独立的 Web 服务获取数据,一个用于获取员工的 JSON 列表,另一个用于获取公司的 JSON 列表。公司将其员工列为 employeeID 数组,而员工将其工作的公司列为逗号分隔字符串,不作为引用。

我的做法是:

1) 我确保从一个空数据库开始

2) 我从员工提要中填充我的核心数据

3) 我填充我的公司实体,设置与他们拥有的每个员工的关系(这就是问题所在)

4) 我想显示公司列表及其相关员工

问题是,一个公司可以雇佣几个员工,每个员工可以为0到n个企业工作。所以当我创建我的第一家公司时,我将它链接到它的员工并且一切正常,但是当我创建我的第二家公司并将它链接到前一家公司的员工时,前一家公司失去了与该员工的关系。

经过一些研究,我没有发现类似的问题(可能是因为我还是一个核心数据新手我没有找对地方),但我发现了这篇文章: http://codekea.com/3J1AZNYRkAMr/setting-core-data-relationship-reusing-same-object-removes-previous-relation.html这似乎是完全相同的问题。由于答案没有解决我的问题(代码将不再编译),我想我应该创建一个示例项目来说明它。

该项目可以从这里下载进行测试: https://www.dropbox.com/s/qi65sh52wwe6ws3/test.zip?dl=0

我的代码如下(我用的是SwiftyJSON):

let mURLEmployees       = NSURL(string: "http://pastebin.com/raw.php?i=ZhmHCmwQ")
let mURLCompanies = NSURL(string: "http://pastebin.com/raw.php?i=LCbvyvqv")

override func viewDidLoad() {
super.viewDidLoad()

//==============================================
// 1)
// EMPTY THE DATABASE
//==============================================


var error: NSError? = nil

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

let request = NSFetchRequest(entityName: "Employee")

let entities = context.executeFetchRequest(request, error: nil) as! [NSManagedObject]

for entity in entities {
context.deleteObject(entity)
}

let request2 = NSFetchRequest(entityName: "Company")

let entities2 = context.executeFetchRequest(request2, error: nil) as! [NSManagedObject]

for entity in entities2 {
context.deleteObject(entity)
}

if !context.save(&error) {
println("An error occured while deleting entities : \(error?.localizedDescription)")
}


//==============================================
// 2)
// POPULATE EMPLOYEES
//==============================================



let entityEmployee = NSEntityDescription.entityForName("Employee", inManagedObjectContext: context)


let JSONEmployeesString = NSString(contentsOfURL: mURLEmployees!, encoding: NSUTF8StringEncoding, error: &error) as! String

var dataJSON = JSONEmployeesString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

var json = JSON(data: dataJSON!)

if let employees = json["features"].array {
for employee in employees {

let employeeObject = Employee(entity: entityEmployee!, insertIntoManagedObjectContext: context)

employeeObject.name = employee["properties"]["NAME"].string!
employeeObject.companies = employee["properties"]["COMPANIES"].string!

if !context.save(&error) {
println("An error occured while saving employees : \(error?.localizedDescription)")
}

}
}



//==============================================
// 3)
// POPULATE COMPANIES
//==============================================



let JSONCompaniesString = NSString(contentsOfURL: mURLCompanies!, encoding: NSUTF8StringEncoding, error: &error) as! String

dataJSON = JSONCompaniesString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

json = JSON(data: dataJSON!)
if let companies = json["features"].array {
for company in companies {


let employees = company["properties"]["EMPLOYEES"].array!

var employeeObjects = NSMutableSet()

for employee in employees {

let predicateEmployeeName = NSPredicate(format: "name == %@", employee.string!)
let DBRequestEmployeeObject = NSFetchRequest(entityName: "Employee")
DBRequestEmployeeObject.predicate = predicateEmployeeName
let EmployeeResultArray = context.executeFetchRequest(DBRequestEmployeeObject, error: nil) as! [Employee]
if let EmployeeResult = EmployeeResultArray.first {
employeeObjects.addObject(EmployeeResult)
} else {
println("ERROR")
}
}

let entityCompany = NSEntityDescription.entityForName("Company", inManagedObjectContext: context)

let companyObject = Company(entity: entityCompany!, insertIntoManagedObjectContext: context)

companyObject.name = company["properties"]["NAME"].string!
companyObject.employees = employeeObjects


if !context.save(&error) {
println("An error occured while saving companies : \(error?.localizedDescription)")
}

}
}


//==============================================
// 4)
// RESULT
//==============================================


let requestCompanies = NSFetchRequest(entityName: "Company")
let companies = context.executeFetchRequest(requestCompanies, error: nil) as! [Company]
println("Number of companies : \(companies.count)")

for company in companies {
println("\(company.name)")

for employee in company.employees {
println("->\(employee.name)")
}

}



}

我的数据模型如下所示:

enter image description here

最佳答案

您的关系是多对多的,在您的 Employee managedObject 中,您需要具有“公司”关系而不是属性。那么你必须重新生成你的托管对象子类。

然后在不设置公司关系的情况下创建所有员工实体(使用您的循环)。然后创建公司,并在为每个公司创建公司时获取员工,然后将他们添加到公司companyObject.employees = employeeObjects

关于ios - 核心数据一对多关系在创建新关系时被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32570115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com