create a Compound Predicate in coreData xcode iphone - iphone

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

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)

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)

Searchbar with core data issues

I have a search bar.And data displayed in labels with scrollview.
For ex:
core data Fields :
1.id
2.company
3.Employe Name
4.Address
If i type id,company or Employee Name in searchbar i want to dispaly associated results.
my code :
For search data :
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
var request = NSFetchRequest(entityName: "Agency")
request.returnsObjectsAsFaults = false
var countResult : NSArray = context.executeFetchRequest(request, error: nil)!
let result = NSPredicate(format: "SELF CONTAINS[c] %#",searchText)
self.filtered = self.countResult.filteredArrayUsingPredicate(result!)
if (filtered.count == 0 ) {
searchActive = false;
}else {
searchActive = true;
}
println(filtered)
}
It shows an error " 'Can't use in/contains operator with collection".
These codes cannot satisfy what i want.And also i dont have a idea how to fetch the related rows according to enter value in search bar.
Thanks in Advance.
The first problem is your predicate - you're trying to use CONTAINS on an NSManagedObject subclass, but CONTAINS only works with String. To check whether your search text is contained within any of your managed objects you need to evaluate whether it is contained in each attribute (in your case id, company and empolyeeName, I'm assuming they're all Strings).
To do this you should change your predicate to:
let searchPredicate = NSPredicate(format: "id BEGINSWITH %# OR
company BEGINSWITH %# OR
employeeName BEGINSWITH %#",
searchText, searchText, searchText)
I would recommend using BEGINSWITH instead of CONTAINS[c] since when searching your user is likely to be entering the first part of the phrase. Also, as Apple said in their 2013 WWDC talk Core Data Performance Optimization and Debugging -
...we've got begins with and ends with and that's by far the cheapest query that you can execute.
...
Contains is more expensive because we have to work along and see
whether it contains...
And in the case of a search, you want it to be fast!
Secondly, you don't need to filter your results after getting them back from CoreData. You can set the predicate property on your NSFetchRequest and your returned results will be filtered. For example:
let request = NSFetchRequest(entityName: "Agency")
request.predicate = // Your predicate...
let results = context.executeFetchRequest(request, error)
// Now do what you need with the results.
A final note, it's best not to force unwrap your results from executeRequest in case there is some problem and nil is returned - in that case your app would crash. You could instead use:
if let unwrappedResults = results {
// Now do what you want with the unwrapped results.
}
I suspect it has something to do with your use of SELF in the predicate format, and the "collection" referred to in the error message is the controller sub/class within which your code resides.
Try something like this (forgive me I'm Obj-C not Swift so may have the syntax incorrect).
let searchAttribute = <<entity.attribute key path>>
let result = NSPredicate(format:"%K CONTAINS[cd] %#",searchAttribute, searchText)
Where %K refers to the key path, that in the case of Core Data is your entity attribute. For example: Agency.name if that attribute exists for your Agency object.
Read about Predicate Format String Syntax.
UPDATE after third comment...
In my apps my solution includes the creation of a custom method in an extension of the Core Data generated NSManagedObject subclass. If that sounds like you know what I mean, let me know and I will post details.
In the meantime, create a custom method in whatever class your UISearchBar is controlled... (apologies Obj-C not Swift)
- (NSString *)searchKey {
NSString *tempSearchKey = nil;
NSString *searchAtrribute1 = Agency.attribute1;
NSString *searchAtrribute2 = Agency.attribute2;
NSString *searchAtrribute3 = Agency.attribute3;
NSString *searchAtrribute4 = Agency.attribute4;
tempSearchKey = [NSString stringWithFormat:#"%# %# %# %#", searchAtrribute1, searchAtrribute2, searchAtrribute3, searchAtrribute4];
return tempSearchKey;
}
You'll obviously need a strong reference for your Agency entity object to persist within the class, otherwise you will need to embed this bit of code into your searchBar function.
Work OK?

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.

Why doesn't this NSPredicate work?

I have a very simple NSPredicate as such:
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:#"name beginswith '%#'", theString];
[matchingTags filterUsingPredicate:sPredicate];
This causes the array to have 0 results when theString == "p"
However, when I do this:
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:#"name beginswith 'p'"];
[matchingTags filterUsingPredicate:sPredicate];
I get over 100 results, as expected.
I have checked "theString" with NSLog() and its value is correct. I feel like I am missing some crucial secret. Possibly because I am using a string and not a character?
Thoughts?
Check out the documentation here
If you use variable substitution using
%# (such as firstName like %#), the
quotation marks are added for you
automatically.
So basically, it's looking for names that start with "p", instead of p. Changing your code to:
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:#"name beginswith %#", theString];
should work