使用objectID获取核心数据

时间:2016-05-19 18:23:31

标签: swift core-data

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

Product

Attendance

我正在拯救出勤关系良好的产品!现在,我需要使用特定的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)")
    }

}

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

1 个答案:

答案 0 :(得分:2)

fetch SELF内部与NSManagedObjectIDNSManagedObject相当。但是,您无法对正在获取的项目执行.objectID。我的理论是,这是因为在执行.时,它正在寻找.objectID属于NSManagedObject的特定实体的属性和/或关系。我可能错了。

但是,如果您只是将NSPredicate切换为其中一个,那么它将起作用。

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

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