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)
Related
I have an entity in my CoreData setup that uses two strings: "name" and "stadium".
I'm trying to write a function that takes a "name" as a parameter, does a CoreData fetch and returns the corresponding "stadium" string value for that "name" entity. This seems like it shouldn't be too hard but I don't know where to start...
Thanks
You should use NSPredicate for filtering.
let fetchRequest = NSFetchRequest<Team>(entityName: "Team")
fetchRequest.predicate = NSPredicate(format: "name == %#", nameToFind)
fetchRequest.fetchLimit = 1
let team = (try? context.fetch(fetchRequest))?.first
return team?.stadium
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 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!)
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.
HI i am working on the core data with 3 entities (Class,Students,ExamRecord) and their relations area as :
Class<------>> Students <------> ExamRecord
I created a predicate for fetching list of students for class 5th.
NSString * fmt2 = #"studentsToClass.className=%#";
NSPredicate * p2 = [NSPredicate predicateWithFormat:fmt2,#"5th",nil];
with this i am getting all students of class 5th
Now i also want to apply another filter on the Students fetched.
Fetch students whose Exam Record "result" is "Pass".result is an attribute for student in ExamResult entity
How can i make use of Compound predicate in this ?
Please correct me if i am wrong
Any help will be appreciated
Thanks
You can use a compound predicate:
NSPredicate *p1 = [NSPredicate predicateWithFormat:#"studentsToClass.className = %#", #"5th"];
NSPredicate *p2 = [NSPredicate predicateWithFormat:#"studentsToExamRecord.result = %#", #"Pass"];
NSPredicate *p = [NSCompoundPredicate andPredicateWithSubpredicates: #[p1, p2]];
Or you simply combine the tests with "AND":
NSPredicate *p = [NSPredicate predicateWithFormat:#"studentsToClass.className = %# AND studentsToExamRecord.result = %#",
#"5th", #"Pass"];
Note that the argument list of predicateWithFormat is not nil-terminated.
The number of arguments is determined by the number of format specifiers in the format
string.
First, you shouldn't really call the student - class relation studentsToClass. The name of the relation should reflect what type of object is at the other end.
E.g.
In this case the Student relation to Class should be called class because the object there is a single Class entity.
The inverse relation should not be called classToStudent it should be called students because the object there is a NSSet of multiple Students.
EDIT
Just to add to this. The name of the relation should explain WHY it is there. We can see that the relation is from class to student but if you call it "classToStudent" it doesn't explain anything. Also, what if you have a second relation from class to student? What do you call that. If you call it attendees or pupils or attendingStudents etc.. it gives the relation meaning.
SOLUTION
In this example I'm going to call them how I would call them and you will see it makes it a bit easier to understand...
Anyway...
NSPredicate *classPredicate = [NSPredicate predicateWithFormat:#"class.className = %#", #"5th"];
NSPredicate *passPredicate = [NSPredicate predicateWithFormat:#"result.name = %#", #"Pass"];
NSCompoundPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:#[classPredicate, passPredicate]];
First, your quoted predicate is really already wrong. You should reference the managed object, not its property (i.e. not the name of the Class). It should be:
[NSPredicate predicateWithFormat:#"class = %#", classObject];
Also, you should really choose more readable names for your variables and property. So, not fmt2 but formattingString. Not studentsToClass but form ("class" is a special word in objective-C). You get the idea.
So your desired compound predicate is done like this (short version):
[NSPredicate predicateWithFormat:#"class = %# && record.result = %#",
classObject, #"Pass"];
The complicated version, if you really need a higher level of abstraction (which I doubt):
classPredicate = [NSPredicate predicateWithFormat:#"class = %#", classObject];
resultPredicate = [NSPredicate predicateWithFormat:#"record.result = %#", #"Pass"];
finalPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:
#[classPredicate, resultPredicate]];
Predicates can also be nested using compounded predicates (For Swift)
let orPredicate = NSCompoundPredicate(type: .or, subpredicates: [date_1KeyPredicate, date_2KeyPredicate])
let functionKeyPredicate = NSPredicate(format: "function_name = %#", self.title!)
let andPredicate = NSCompoundPredicate(type: .and, subpredicates: [orPredicate, functionKeyPredicate])