Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining Two Conditions in NSPredicate

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!)
like image 768
Simon Avatar asked Oct 24 '15 17:10

Simon


People also ask

What is a predicate in SQL?

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.

How can I create predicates that include variables?

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.

What is a combined condition in Python?

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.

What happens when you combine two conditions in an IF statement?

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.


3 Answers

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.

like image 156
Martin R Avatar answered Oct 19 '22 16:10

Martin R


Try this

request.predicate = NSPredicate(format: "username = %@ AND password = %@", txtUserName.text!, txtPassword.text!)
like image 40
Alexander Avatar answered Oct 19 '22 14:10

Alexander


AND is exactly what you need

request.predicate = NSPredicate(format: "username = %@ AND password = %@", txtUserName.text!, txtPassWord.text!)
like image 1
vadian Avatar answered Oct 19 '22 14:10

vadian