NSfetchRequest不返回任何内容

时间:2019-07-08 11:52:58

标签: swift core-data nsfetchrequest

从核心数据库获取数据并同时更新同一实体的数据时,fetchRequest返回nil

let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Abc")
        fetchRequest.predicate = NSPredicate(format: "id = %@ ", productID)

    do {
        let product = try mainContext.fetch(fetchRequest).first
        return product as? Products
    } catch _ as NSError {
        //print("Could not fetch. \(error), \(error.userInfo)")
        return nil
    }

1 个答案:

答案 0 :(得分:0)

该实体与结果的强制类型不匹配

要么是

let fetchRequest = NSFetchRequest(entityName: "Abc")

...

do {
    let product = try mainContext.fetch(fetchRequest).first
    return product as? Abc

 let fetchRequest = NSFetchRequest(entityName: "Products")

 do {
    let product = try mainContext.fetch(fetchRequest).first
    return product as? Products

请以单数形式命名实体。语义上,您投射product as? Product