如何在CoreData中获取子条目的所有属性值?

时间:2018-04-17 09:25:06

标签: swift core-data one-to-many nsfetchrequest

我有一个名为“客户”的父实体。

我已经与另一个实体“Debts”

定义了一个OneToMany关系

“Debts”有我的NSManagedObject类中定义的4个属性:

延期债务{

@nonobjc public class func fetchRequest() -> NSFetchRequest<Debts> {
    return NSFetchRequest<Debts>(entityName: "Debts")
}

@NSManaged public var amountDebt: Double
@NSManaged public var dateDebt: NSDate?
@NSManaged public var notesDebt: String?
@NSManaged public var nameDebt: String?
@NSManaged public var debtCust: Customer?}

现在我正在尝试在桌面视图中为所有客户显示所有债务。它自己的视图控制器。

应仅为父实体制作获取请求,还是仅为子实体“债务”或两者制作?

目前,我已经尝试了父实体,但我似乎无法检索属性名称。这真让我抓狂!任何帮助将不胜感激。

我的fetchRequest:

func getFetchedResultsController() -> NSFetchedResultsController<Customer> {

    frc = NSFetchedResultsController(fetchRequest: customerFetchRequest(), managedObjectContext: getContext(), sectionNameKeyPath: nil, cacheName: nil)
    return (frc!)

}

func getContext () -> NSManagedObjectContext {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    return appDelegate.persistentContainer.viewContext
}

func customerFetchRequest() -> NSFetchRequest<Customer> {
    let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Customer")

    fetchRequest.relationshipKeyPathsForPrefetching = ["Debts"] //Not Sure about this line

    let sortDescriptor = NSSortDescriptor(key: "postcode", ascending: true)
    fetchRequest.sortDescriptors = [sortDescriptor]

    return fetchRequest as! NSFetchRequest<Customer>
}

以上不会引发错误,但如果错误,我如何访问“债务”的各种属性

我已经尝试按照下面的指示获取“债务”,但即使保存到债务我仍未收到错误,但仍然没有结果。我怀疑我没有正确保存数据。这是我保存一对多关系的属性值的代码:

    let newDebt = NSEntityDescription.entity(forEntityName: "Debts", in: context)
    let debt = Debts(entity: newDebt!, insertInto: context)

    debt.amountDebt = 2.50
    debt.notesDebt = "Some Note"
    debt.nameDebt = "Customer Name"
    debt.dateDebt = Date()

    cust.addToCustDebts(debt)

    //save the object

    do {
        try context.save()
        print("Save Success")
    }

0 个答案:

没有答案