2016-10-06 22 views
1

我似乎无法找到属于在斯威夫特滤芯数据的任何好的文档或教程3需要帮助斯威夫特滤芯数据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”字段等于先前设置的变量的内容(在本例中为“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.") 
} 
+0

[“核心数据编程指南”(https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData /) - >“获取对象” - >“过滤结果”。 –

回答

5

您需要连接到请求的谓词:

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