未保存核心数据继承实体

时间:2018-04-24 07:41:55

标签: swift inheritance core-data

我在核心数据中有以下数据模型: enter image description here

*注意:我设置AttachmentAbstractExpenseAttachmentLeaveAttachment的父级设为Attachment

当我尝试保存ExpenseAttachmentLeaveAttachment时,我会介绍一个问题,即保存新附件的代码运行良好而没有错误,但没有真正发生,因为当我尝试检索它没有记录。

所以我使用这段代码保存:

func syncExpenseAttachments(attachmentResponse: AttachmentResponse, expenseID: Int64)
{
    let backgroundContext : NSManagedObjectContext! = DataController.sharedInstance().backgroundContext

    backgroundContext.perform
    {
        let attachmentExpense = try? backgroundContext.fetch(Expense.fetchRequest()).filter { $0.tkID == expenseID }

        let attachment = ExpenseAttachment(context: backgroundContext)
        attachment.tkID = Int64(attachmentResponse.id ?? 0)
        attachment.createdDate = attachmentResponse.createdDate ?? Date()
        attachment.name = attachmentResponse.name ?? ""
        attachment.flaggedForDelete = false
        attachment.data = attachmentResponse.data as Data? ?? nil

        if let attachmentExpense = attachmentExpense {
            attachment.expense = attachmentExpense[0]
        }

        try? backgroundContext.save()

    }
}

这段代码来获取记录:

let attachmentRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ExpenseAttachment")
let sortDescriptor = NSSortDescriptor(key: "name", ascending: false)
attachmentRequest.sortDescriptors = [sortDescriptor]

do {
    let coreDataExpenseAttachments = try DataController.sharedInstance().viewContext.fetch(attachmentRequest) as! [ExpenseAttachment]

    //Do some work

} catch {
    print(error.localizedDescription)
}

保存后,尝试检索附件不会返回任何内容。但是,如果我只是简单地使用Attachment实体进行保存,那么当我还尝试检索附件enitity的数据时,我实际上可以看到记录。我虽然你不创建或保存抽象父实体,只是孩子实体?

0 个答案:

没有答案