使用 objectID 获取核心数据

sda*_*sad 2 core-data swift

我的数据模型中有 2 个实体,如下图所示:

产品:
产品

出席:
出勤率

我很好地保存了出勤关系的产品!现在,我需要使用特定的 Attendance.objectID 获取产品

我正在尝试以下代码:

func fetchProducts() {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    
    let managedContext = appDelegate.managedObjectContext
    
    let fetchRequest = NSFetchRequest(entityName: "Product")
    let attendancePredicate = NSPredicate(format: "attendance.objectID == \(currAttendance.objectID)")
    fetchRequest.predicate = attendancePredicate
    
    print("Att = \(currAttendance.name!)")
    viewTypeSKU.hidden = true
    
    do {
        let results = try managedContext.executeFetchRequest(fetchRequest)
        products = results as! [NSManagedObject]
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }

}
Run Code Online (Sandbox Code Playgroud)

我收到错误: 'Unable to parse the format string "attendance.objectID ==

boi*_*kan 5

在 fetchSELF中与NSManagedObjectIDNSManagedObject. 但是,您不能.objectID对正在获取的项目进行操作。我的理论是,这是因为在执行此操作时,.它正在寻找.objectID属于NSManagedObject. 不过我可能是错的。

但是,如果您只是将 NSPredicate 切换到其中之一,它将起作用。

NSPredicate(format: "attendance == %@", currAttendance.objectID)

或者

NSPredicate(format: "attendance == %@", currAttendance)