需要帮助过滤Swift 3中的核心数据

时间:2016-10-06 01:29:40

标签: core-data filtering swift3 nspredicate

我似乎无法找到任何与Swift 3中的核心数据过滤相关的优秀文档或教程。

我有以下代码:

let tempVar: String = "abcdef"

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

do {

    /* Need code to modify the fetchRequest, so that it only pulls results where the "projectID" field is equal to whatever is stored in the tempVar variable. */

    cstProjectDetails = try context.fetch(CSTProjectDetails.fetchRequest())
} catch {
    print("There was an error fetching CST Project Details.")
}

基本上,我只是想在fetchRequest中添加一个简单的过滤器,以便它只从" cstProjectDetails"中提取结果。 " projectID" field等于先前设置的变量的内容(在这种情况下," tempVar")。

有什么想法吗?

编辑:已检查的答案对我有用,但我必须快速调整请求初始值设定项的代码。这是我最终得到的代码:

do {
    let request: NSFetchRequest<CSTProjectDetails> = CSTProjectDetails.fetchRequest()
    request.predicate = NSPredicate(format: "projectID == %@", cstProjectID)
    cstProjectDetails = try context.fetch(request)
    print(cstProjectDetails)
} catch {
    print("There was an error fetching CST Project Details.")
}

1 个答案:

答案 0 :(得分:6)

您需要在请求中附加谓词:

let request = CSTProjectDetails.fetchRequest()
request.predicate = NSPredicate(format: "projectID == %@", tempVar)
cstProjectDetails = try context.fetch(request)