【问题标题】:Resolving core data relationship raising SIGABRT error解决核心数据关系引发 SIGABRT 错误
【发布时间】:2019-09-28 00:29:57
【问题描述】:

我正在使用 swift playground 重新学习 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的员工

我相信这种关系已经建立起来了。

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

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

感谢

【问题讨论】:

  • 好吧,我将成为一个无聊的人,但不是使用操场创建支持 Core Data 的常规项目的最简单方法吗?
  • 我只是希望暂时将它分开,这样我就可以理解基础知识,而无需维护整个 xcode 项目的开销。我明白你在问什么,是的,我同意。我只是想先做一些基本的事情。

标签: swift core-data


【解决方案1】:
...
tom.setValue(Set([companyABC]), forKey: "company")
...
sarah.setValue(Set([companyDelta]), forKey: "company")
...

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

来自doc

Destination 弹出菜单定义在代码中访问关系时返回的对象(或对象)。如果关系定义为一对一,则返回单个对象(如果关系可以是可选的,则返回 nil)。 如果关系定义为多对多,则返回一个集合(如果关系可以是可选的,则返回 nil)。

【讨论】:

  • 这似乎行得通。我感谢及时的反馈。我不知道我必须将关系属性设置为 set,但感谢您的帮助
  • @zardon 文档规范已添加 ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
  • 1970-01-01
  • 2012-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多