John Hubler
John Hubler

Reputation: 909

Need help filtering core data in Swift 3

I can't seem to find any good documentation or tutorials that pertain to filtering core data in Swift 3.

I have the following code:

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.")
}

Basically, I am just trying to do add a simple filter to the fetchRequest, so that it only pulls results from "cstProjectDetails" where the "projectID" field is equal to the contents of a previously set variable (in this case, "tempVar").

Any ideas?

Edit: The checked answer did the trick for me, but I had to make a quick adjustment to the code for the request initializer. Here is the code that I ended up with:

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.")
}

Upvotes: 1

Views: 5415

Answers (1)

vadian
vadian

Reputation: 285250

You need a predicate attached to the request:

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

Upvotes: 6

Related Questions