37

Ok I have a basic iPad app that asks for 5 search/filter criteria from the user. Based on this data, I need to go to my core data db, and pull out any managed objects that fit that criteria. It seems like I need to apply more than one predicate to the same request, is that possible? Or could I just write a really long fancy predicate? With multiple requirements? How should I approach that?

Would it be a good idea to just grab all the entities through the fetch request, and then loop through each array and grab any objects that I find that fit my search criteria?

Please advise!

Lizza
  • 2,769
  • 5
  • 39
  • 72

3 Answers3

90

Yes it's possible. You're looking for compound predicates and here's an example with AND predicates:

NSPredicate *compoundPredicate 
   = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray of Predicates]];

You can also use notPredicateWithSubpredicates and orPredicateWithSubpredicates depending on your needs.

Link to documentation https://developer.apple.com/documentation/foundation/nscompoundpredicate

Cœur
  • 37,241
  • 25
  • 195
  • 267
Rog
  • 18,602
  • 6
  • 76
  • 97
  • 3
    Thanx man, I tried doing this by composing a NSString and passing it to predicate as format. This worked well but not for dates!! i wasted a day of work. This is the way to create filters :D – MQoder Jul 21 '14 at 22:44
8

Swift 4

let fetchRequest: NSFetchRequest<YourModelEntityName> = YourModelEntityName.fetchRequest()

let fooValue = "foo"
let barValue = "bar"

let firstAttributePredicate = NSPredicate(format: "firstAttribute = %@", fooValue as CVarArg)
let secondAttributePredicate = NSPredicate(format: "secondAttribute = %@", barValue as CVarArg)

fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [firstAttributePredicate, secondAttributePredicate])

more information about different types of NSCompoundPredicate constructors can be found here

den
  • 336
  • 2
  • 12
0

yes you can apply like this below

do {
            let request = UserDeatils.fetchRequest() as NSFetchRequest<UserDeatils>
            
            let firstAttributePredicate = NSPredicate(format: "userName = %@", userNameTextField.text!)
            let secondAttributePredicate = NSPredicate(format: "password = %@", passwordTF.text!)

        request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [firstAttributePredicate, secondAttributePredicate])
        
        
        self.userDataArray = try context.fetch(request)
        print("Fetching Data", userDataArray)
        
        if userDataArray.isEmpty {
            print("no user found")
            
        } else {
            print("Login Succesfully")
            
              
        }
    } catch {
        print("Wrong Username and password")
    }

enter image description here

enter image description here