Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 596
MVZ Avatar asked Feb 26 '15 23:02

MVZ


2 Answers

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

let filter = "products"
let predicate = NSPredicate(format: "type = %@", filter)
fetchRequest.predicate = predicate
like image 110
Ian Avatar answered Sep 27 '22 17:09

Ian


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)
}
like image 34
Talha Rasool Avatar answered Sep 27 '22 17:09

Talha Rasool