MVZ
MVZ

Reputation: 2250

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"?

Upvotes: 15

Views: 18042

Answers (3)

Talha Rasool
Talha Rasool

Reputation: 1152

So, in the below example

  1. In the first step, we will add give the value we want to filter.
  2. In the second step, we will add a predicate in which we will give the DB key we want to get the value in my case is "id" and besides this a value, we want to filter.
  3. In the Third step assign the entity name where your all data has saved in the NSFetchRequest.
  4. After that assign the predicate.
  5. Use context object to fetch the object.
private let context = (NSApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        
let filter = id
let predicate = NSPredicate(format: "id = %@", filter)
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"TodoListItem")
fetchRequest.predicate = predicate
                    
do{
    let fetchedResults = try context.fetch(fetchRequest) as! [NSManagedObject]
    print("Fetch results")
    if  let task = fetchedResults.first as? TodoListItem{
        print(task)
    }
                      
    //  try context.save()
            
}catch let err{
    print("Error in updating",err)
}

Upvotes: 3

apurva kochar
apurva kochar

Reputation: 49

You can use .filter on the fetchedResults.

Upvotes: 0

Ian
Ian

Reputation: 12768

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

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

Upvotes: 38

Related Questions