gpt4 book ai didi

swift - 解决引发 SIGABRT 错误的核心数据关系

转载 作者:行者123 更新时间:2023-11-28 05:37:35 25 4
gpt4 key购买 nike

我正在使用 swift playground 重新学习 swift 核心数据基础知识。

我正在手写核心数据来编写一个简单的 Playground 应用

One Company has many Employees

我经常遇到错误:

error: Execution was interrupted, reason: signal SIGABRT.

当谈到挽救公司与单个员工之间的关系时,我不确定为什么会提出这个问题。

我的代码如下:

// Swift playground code
import CoreData

class NotificationListener: NSObject {
@objc func handleDidSaveNotification(_ notification:Notification) {
print("did save notification received: \(notification)")
}
}

let listener = NotificationListener()
NotificationCenter.default.addObserver(listener, selector: #selector(NotificationListener.handleDidSaveNotification(_:)), name: NSNotification.Name.NSManagedObjectContextDidSave, object: nil)


// Define managed object
let model = NSManagedObjectModel()

//: [Entities]

let companyEntity = NSEntityDescription()
companyEntity.name = "Company"

let employeeEntity = NSEntityDescription()
employeeEntity.name = "Employee"
employeeEntity.indexes = []

//: [Attributes]

let companyNameAttribute = NSAttributeDescription()
companyNameAttribute.name = "name"
companyNameAttribute.attributeType = NSAttributeType.stringAttributeType
companyNameAttribute.isOptional = false

let countryAttribute = NSAttributeDescription()
countryAttribute.name = "country"
countryAttribute.attributeType = NSAttributeType.stringAttributeType
countryAttribute.isOptional = false

let employeeNameAttribute = NSAttributeDescription()
employeeNameAttribute.name = "name"
employeeNameAttribute.attributeType = NSAttributeType.stringAttributeType
employeeNameAttribute.isOptional = false

let ageAttribute = NSAttributeDescription()
ageAttribute.name = "age"
ageAttribute.attributeType = NSAttributeType.integer16AttributeType
ageAttribute.isOptional = false

// Relationships

let companyRelationship = NSRelationshipDescription()
let employeeRelationship = NSRelationshipDescription()

companyRelationship.name = "company"
companyRelationship.destinationEntity = companyEntity
companyRelationship.minCount = 0
companyRelationship.maxCount = 0
companyRelationship.deleteRule = NSDeleteRule.cascadeDeleteRule
companyRelationship.inverseRelationship = employeeRelationship

employeeRelationship.name = "employees"
employeeRelationship.destinationEntity = employeeEntity
employeeRelationship.minCount = 0
employeeRelationship.maxCount = 1
employeeRelationship.deleteRule = NSDeleteRule.nullifyDeleteRule
employeeRelationship.inverseRelationship = companyRelationship

companyEntity.properties = [companyNameAttribute, countryAttribute, employeeRelationship]
employeeEntity.properties = [employeeNameAttribute, ageAttribute, companyRelationship]

model.entities = [companyEntity, employeeEntity]

// Create persistent store coordinator
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel:model)

do {
try persistentStoreCoordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil)
} catch {
print("error creating persistentStoreCoordinator: \(error)")
}

let managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator

// Companies
let companyABC = NSEntityDescription.insertNewObject(forEntityName: "Company", into: managedObjectContext)
companyABC.setValue("ABC Ltd", forKeyPath: "name")
companyABC.setValue("United States", forKeyPath: "country")

let companyDelta = NSEntityDescription.insertNewObject(forEntityName: "Company", into: managedObjectContext)
companyDelta.setValue("Delta", forKeyPath: "name")
companyDelta.setValue("Canada", forKeyPath: "country")

let tom = NSEntityDescription.insertNewObject(forEntityName: "Employee", into: managedObjectContext)
tom.setValue("Tom", forKey: "name")
tom.setValue(22, forKey: "age")
tom.setValue(companyABC, forKey: "company") // <<-- Throws error

let sarah = NSEntityDescription.insertNewObject(forEntityName: "Employee", into: managedObjectContext)
sarah.setValue("Sarah", forKey: "name")
sarah.setValue(41, forKey: "age")
sarah.setValue(companyDelta, forKey: "company") // <<-- Throws error



func save(context: NSManagedObjectContext) {

// Save context
do {
try context.save()
} catch {
print("error saving context: \(error)")
}

let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Company")

var results: [NSManagedObject] = []

do {
results = try managedObjectContext.fetch(fetchRequest)

print ("\n#\(results.count) records found\n")

} catch {
print("error executing fetch request: \(error)")
}

print("results: \(results)")
}

save(context: managedObjectContext)

当它试图拯救一名员工时,问题就来了:

let tom = NSEntityDescription.insertNewObject(forEntityName: "Employee", into: managedObjectContext)
tom.setValue("Tom", forKey: "name")
tom.setValue(22, forKey: "age")
tom.setValue(companyABC, forKey: "company")

尝试将 companyABC 设置为 tom 对象的关系时出现错误。

目标是让 TomcompanyABC 的员工

我相信这种关系已经正确建立。

但我不确定是什么导致了错误。

因此,我的问题是:如何解决这个错误?

谢谢

最佳答案

...
tom.setValue(Set([companyABC]), forKey: "company")
...
sarah.setValue(Set([companyDelta]), forKey: "company")
...

因为在这种情况下,如果您使用 XCode 从 CoreData Graph 生成类模型,它会生成属性 company(NS)Set< 的对象 我认为它应该写在 CoreData 文档的某处,但不幸的是 set 是一个太常见的词。 编辑,找到它。

来自doc :

The Destination pop-up menu defines what object (or objects) is returned when the relationship is accessed in code. If the relationship is defined as to-one, a single object (or nil if the relationship can be optional) is returned. If the relationship is defined as to-many, a set is returned (or again, nil if the relationship can be optional).

关于swift - 解决引发 SIGABRT 错误的核心数据关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58137257/

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