Search code examples
swiftcore-data

Swift: How to filter in Core Data


I'm using the following code to fetch all the data in "category".

let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate

let managedContext = appDelegate.managedObjectContext!
let fetchRequest = NSFetchRequest(entityName:"category")
let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as [NSManagedObject]?

How do I only brings categories where the "type" is equal to "products"?


Solution

  • To "filter" results in Core Data, use NSPredicate like so:

    let filter = "products"
    let predicate = NSPredicate(format: "type = %@", filter)
    fetchRequest.predicate = predicate