Combining Two Conditions in NSPredicate - swift

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!)

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!)

Related

Searching 2 Attributes at the same time CoreData

I'm trying to use a predicate to search 2 attributes at the same time. I initially tried a compound predicate but it would only return results if both predicates matched the string.
Basically I'm looking for something similar to this:
let predicate = NSPredicate(format: "title CONTAINS[cd] %#" || "plainTextBody CONTAINS[cd] %#", searchString, searchString)
So it seems I was close with my original post but it's important to keep the search terms in quotation marks and not separate them like I did in my original question. Simply using the following works perfectly:
let predicate = NSPredicate(format: "title CONTAINS[cd] %# || plainTextBody CONTAINS[cd] %#", searchString, searchString)

CoreData predicate using relationship

I have two entities - Quotes and Customers. One customer can have many quotes. The relationships are quotes and customers.
I want to get a quote object based on the customer name and email address, sorted by date but I'm stuck trying to format the predicate...
func getMostRecentQuote(name: String, email: String) -> Quotes? {
var predicateList = [NSPredicate]()
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Quotes")
let predicate1 = NSPredicate(format: "name CONTAINS[c] %#", name)
let predicate2 = NSPredicate(format: "email CONTAINS[c] %#", email)
let orCompoundPredicate = NSCompoundPredicate(type: .or, subpredicates: [predicate1, predicate2])
predicateList.append(orCompoundPredicate)
fetchRequest.predicate = NSCompoundPredicate(type: .and, subpredicates: predicateList)
fetchRequest.fetchLimit = 1
Probably you have a to-one relationship from Quotes to Customers, if not, establish one and name the property customer
Then use this single predicate
let predicate = NSPredicate(format: "customer.name CONTAINS[c] %# OR customer.email CONTAINS[c] %#", name, email)
If you want to filter the full string caseinsensitive CONTAINS is actually the wrong operator, better use LIKE
let predicate = NSPredicate(format: "customer.name LIKE[c] %# OR customer.email LIKE[c] %#", name, email)
 
Note: Please name entities in singular form, semantically your method is going to return one Quote, not one Quotes

How to sort ckrecords by userID?

How should I go about creating an nspredicate that checks the userID of a record in swift?
let userID = "__defaultOwner__"
let predicate = NSPredicate(format: "keyToUseHere == %#", userID)
What should I put in place of the 'keyToUseHere' in the nspredicate to sort by the creator's id?
You need to use the key which can be property of your model class something like this:-
let predicate = NSPredicate(format: "userID" == %#", userIDValue)

Filter navigation properties of one-to-many

I have a model Category with the relationship property articles with is an NSOrderedSet.
Now I want to get all Categories with the articles where a certain condition is fulfilled, in SQL I would write:
SELECT *
FROM Category AS cat
JOIN Article AS art ON art.categoryId = cat.categoryId AND art.gender='m';
I tried with:
NSPredicate(format: "articles.gender like %# OR articles.gender = %#", gender.lowercased(), "n")
I get the following error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'to-many key not allowed here'
Complete code:
let ctx = self.Context()
var gender = UserDefaults.standard.string(forKey: "gender_preference") ?? "*"
if gender.uppercased() == "N" { gender = "*" }
// Create Fetch Request
let fetchRequest: NSFetchRequest = ArticleCategory.fetchRequest()
let predicate = NSPredicate(format: "articles.gender like %# or articles.gender = %#", gender, "n")
fetchRequest.predicate = predicate
// sort by name
let sort = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sort]
do {
let result = try ctx.fetch(fetchRequest)
return result
} catch {
print(error)
}
return []
Kind Regards
EDIT:
I find it's more reliable to use SUBQUERY rather than ANY, ALL, NONE or SOME, particularly with compound clauses. Fetching Categories where ANY of its articles meet a condition is equivalent to fetching if the count of articles meeting the condition is greater than zero:
let predicate = NSPredicate(format: "SUBQUERY(articles, $a, $a.gender like %# OR $a.gender == %#).#count > 0", gender, "n")

CKQuery where predicate has reference and not field?

I need to create a CKQuery where the predicate contains a reference of a record, and not a field of the record.
Like this
let query = CKQuery(recordType: "OUP", predicate: NSPredicate(format: "o = %#", "FF4FB4A9-271A-4AF4-B02C-722ABF25BF44")
How do I set o is a CKReference, not field!
I get this error:
Field value type mismatch in query predicate for field 'o'
You can use a CKRecord or CKRecordID, with or without a CKReference, to match relationships.
CKRecord:
let predicate = NSPredicate(format: "artist == %#", artist)
CKRecordID:
let predicate = NSPredicate(format: "artist == %#", artistID)
CKReference with CKRecord:
let recordToMatch = CKReference(record: artist, action: CKReferenceAction.None)
let predicate = NSPredicate(format: "artist == %#", recordToMatch)
CKReference with CKRecordID:
let recordToMatch = CKReference(recordID: artistID, action: CKReferenceAction.None)
let predicate = NSPredicate(format: "artist == %#", recordToMatch)
I found in CKQuery class reference the answer, or at least an example how to use CKReference in CKQuery:
CKReference* recordToMatch = [[CKReference alloc] initWithRecordID:employeeID action:CKReferenceActionNone];
NSPredicate* predicate = [NSPredicate predicateWithFormat:#"employee == %#", recordToMatch];
To match records that link to a different record whose ID you know, create a predicate that matches a field containing a reference object as shown in Listing 1. In the example, the employee field of the record contains a CKReference object that points to another record. When the query executes, a match occurs when the ID in the locally created CKReference object is the same ID found in the specified field of the record.