解决引起SIGABRT错误的核心数据关系

问题描述 投票:0回答:1

我正在使用Swift游乐场重新学习Swift的核心数据基础。

我正在长时间写出核心数据以编写一个简单的运动场应用,其中>

一个Company有多个Employees

我经常遇到错误:

错误:执行被中断,原因:信号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的员工

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

但是我不确定是什么引起了错误。

因此,我的查询是:如何解决此错误?

谢谢

我正在使用Swift Playground重新学习Swift的核心数据基础知识。我正在长期编写核心数据,以编写一个简单的游乐场应用程序,其中一个公司有很多员工,我一直在...

swift core-data
1个回答
1
投票
...
tom.setValue(Set([companyABC]), forKey: "company")
...
sarah.setValue(Set([companyDelta]), forKey: "company")
...
© www.soinside.com 2019 - 2024. All rights reserved.