How do you combine two conditions in NSPredicate
? I am using the following statement and I would like to add another condition that compares the the password with the contents of a textfield using AND:
request.predicate = NSPredicate(format: "username = %@", txtUserName.text!)
A definition of logical conditions for constraining a search for a fetch or for in-memory filtering. Predicates represent logical conditions, which you can use to filter collections of objects.
You can also create predicates that include variables using the evaluate (with:substitutionVariables:) method so that you can predefine the predicate before substituting concrete values at runtime.
This combination is True when two things happen at the same time: Either A or B is True. And C tests True. When A and B combine to False, and C is False, then the combined condition is False too. Now let’s consider some Python example programs to learn more.
When an if statement requires several True conditions at the same time, we join those different conditions together with the and operator. Such a combined condition becomes False as soon as one condition tests False. Let’s look at some examples. So when we combine conditions with and, both have to be True at the same time.
As already said, you can use logical operators like "AND", "OR" in predicates. Details can be found in Predicate Format String Syntax in the "Predicate Programming Guide".
As an alternative, use "compound predicates":
let p1 = NSPredicate(format: "username = %@", "user")
let p2 = NSPredicate(format: "password = %@", "password")
let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [p1, p2])
This is useful for more complex expressions, or if you want to build a predicate dynamically at runtime.
Try this
request.predicate = NSPredicate(format: "username = %@ AND password = %@", txtUserName.text!, txtPassword.text!)
AND
is exactly what you need
request.predicate = NSPredicate(format: "username = %@ AND password = %@", txtUserName.text!, txtPassWord.text!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With