How can I use NSPredicate to filter on core data relationships? - core-data

Say I have core data objects of type "obj" that has a property "propertyA" and a one-to-many relationship with an object of type "sub" that has two properties, "propertyB" and "propertyC".
I want to fetch all the objs that have propertyA equal to a value and a sub obj with propertyB and propertyC set.
If it was just propertyA and propertyB, I would do
[NSPredicate predicateWithFormat:#"ANY sub.propertyB = %# AND propertyA == %#", ...];
The problem is that I can't figure out how to add in the second property. I want only the objs that have at least one sub that has the two properties true. I've tried the following, but it doesn't work:
[NSPredicate predicateWithFormat:#"ANY (sub.propertyB = %# AND sub.propertyC) AND propertyA == %#", ...];
I've tried it without the ANY but that doesn't work either. How can I do this?

Since you have a to-many relationship with the sub object, the subs property of obj returns a set instead of a single object. To query the set, you need to use a SUBQUERY.
Subqueries have the form:
SUBQUERY(collection, $individualCollectionItem, expression-with-collection-item)
in this case you would want something like
SUBQUERY(subs,$s,$s.propertyB==%#) AND SUBQUERY(subs,$s,$s.propertyC!=NULL)

The solution seems to be:
[NSPredicate predicateWithFormat:#"propertyA == %# AND (SUBQUERY(sub, $s, $s.propertyB == %# AND $s.propertyC == %#).#count != 0)", propertyAvalue, propertyBvalue, propertyCvalue];
where the values at the end are the values you want the various properties to be equal to.

Related

Is a subquery needed for my nspredicate to work properly?

I have an array of custom objects that have beds (1,2,3), fireplace (yes or no), den (yes or no) and ceiling heights (9-11,11-14,14-16). I need to allow filtering based on any/all/none of the items being selected to filter by. So a user may want to see 1 & 2 beds, den, fireplace and 9-11 foot ceilings. Or just 1 & 2 beds. My current predicate works for some of these. But it doesn't match all - only some. I am thinking I need a subquery. How to create a nested(?) subquery based on an array of filters?
Right now, the user selects buttons and those are matched against Filters and I use those to create my predicate.
Current predicate
Filters is an array of keys and predicate strings like 'beds, 1' and 'ceilings, 9-11'
`NSMutableArray *subPredicates = [NSMutableArray array];
for (Filter*fil in filters) {
NSPredicate *unitsPredicate = [NSPredicate predicateWithFormat:#"%K == %#", fil.key, fil.predicate];
[subPredicates addObject:bedsPredicate];
}
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates];
NSLog(#"homes: %#", [searchArray filteredArrayUsingPredicate:predicate]);
NSArray *ar = [searchArray filteredArrayUsingPredicate:predicate];
I'd like to allow someone to pick any of the criteria and return appropriate data.
Subqueries are used with to-many relationships. If you want to filter multiple values then the class of fil.predicate should be an array (or set) of values. The predicate format is %K IN %#, for example
for (Filter*fil in filters) {
NSPredicate *unitsPredicate;
if ([fil.predicate isKindOfClass:[NSArray class]])
unitsPredicate = [NSPredicate predicateWithFormat:#"%K IN %#", fil.key, fil.predicate];
else
unitsPredicate = [NSPredicate predicateWithFormat:#"%K == %#", fil.key, fil.predicate];
[subPredicates addObject:bedsPredicate];
}
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates];
See Aggregate Operations in Predicate Programming Guide.

NSFetchRequest predicate querying correctly, but resulting NSManagedObject showing incorrect fields [duplicate]

I am using UIManagedDocument with Parent Child context.
In my child context I do the following
Code 1
NSSet *results = [self.event.memberships filteredSetUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
return ([[evaluatedObject deleted] boolValue] == NO);
}]];
Above code returns the expected results (only Not deleted members for the event).
Code 2
But this code does not. It fetches all records.
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"deleted == NO"];
NSSet *results = [self.event.memberships filteredSetUsingPredicate:predicate];
It seems confusing. Both should return same results, but predicateWithBlock returns correct results where as predicateWithFormat returns all records.
What are the pros and cons of using predicateWithBlock instead of predicateWithFormat?
The problem is that you have defined an attribute deleted for your entity. That conflicts with the isDeleted method of NSManagedObject, so you should rename that attribute.
The following "experiment" shows that strange things happen if you call your attribute "deleted" (c is a managed object with a custom deleted attribute):
// Set custom "deleted" property to YES:
c.deleted = #YES;
// Use the property, as your Code 1
NSLog(#"%#", [c deleted]);
// Output: 1
// Use Key-Value Coding, as your Code 2
NSLog(#"%#", [c valueForKey:#"deleted"]);
// Output: 0
// Now really delete the object and try again:
[context deleteObject:c];
NSLog(#"%#", [c valueForKey:#"deleted"]);
// Output: 1
Your "Code 1" refers to the property, therefore it returns the expected result. "Code 2" uses Key-Value Coding, and [c valueForKey:#"deleted"] returns YES if the object
actually has been deleted from the context!
So renaming that attribute should solve your problem. Unfortunately the compiler does not
emit warnings if an attribute name conflicts with a built-in method.
Use the formatting placeholder to replace the bool value:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"%K == %#",
#"deleted", #(NO)];
Your use of the key path is probably ok, but the right-hand side probably doesn't look like "NO" to the parser.

Creating Core Data predicate to get data within one-to-many relationship

I have a Loans entity with a returnedDate attribute that can contain a date or be NIL. There is a to-many relationship with another entity, Items such that items can be related to many Loans. I would like to create a predicate where I can find all items that do not currently have a loans.returnedDate==NIL.
Assume I currently have the following:
Loan1-item1,returnedDate=NIL
Loan2-item1,returnedDate=5/4/2012
Loan3-item2,returnedDate=NIL.
I would like a predicate that returns no items.
NSPredicate *pred = [NSPredicate predicateWithFormat:#"!(ANY loaned.returnDate==nil)"];
Returns item1.
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(NONE loaned.returnDate==nil)"];
Returns item1.
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(ANY loaned.returnDate!=nil)"];
Returns item1.
Can someone tell me what logic would return the appropriate results?
So I used the following predicate:
(SUBQUERY(loaned, $sub, $sub.returnDate==nil).#count == 0)
and it is returning the desired results. If you can convince me not to use SUBQUERY, please tell me how.

CoreData: Fetch an object that has a given property AND a given relationship?

I have a CoreData model that looks a bit like this:
Object A:
Results -- A one to many relationship to an indeterminate number of Object B's.
Object B:
Object Name -- A string. (potentially not unique)
Parent -- A singular relationship with Object A.
I am struggling with writing a NSPredicate that will return ObjectB if I know a given Object A and the Object Name string I am looking for. I have tried the following, but always get this error:
"'NSInvalidArgumentException', reason: 'Unable to parse the format string ..."
request.predicate = [NSPredicate predicateWithFormat:#"NameString == %#, SELF IN %#", NameString, ObjectA.results];
request.predicate = [NSPredicate predicateWithFormat:#"(NameString == %#) IN %#", NameString, ObjectA.results];
And so on...
This seems like this should be a simple and obvious thing to do, but I am new at Core Data and am having trouble finding an example that shows this.
Thanks!
You need to use %K.
You may need something like this in your predicate
NSString enitity=#"ObjectA";
NSString attribute=#"results";
request.predicate = [NSPredicate predicateWithFormat:#"NameString == %#, SELF IN %K.%K", NameString, enitity,attributes];
Look here.

CoreData - NSPredicate results if relationship has data

I have a many-to-many relationship between tables, and I populate a tableView with Activities.
For that i user a simple NSPredicate like this:
request.predicate = [NSPredicate predicateWithFormat:#"deleted == %#", [NSNumber numberWithBool:NO]];
How can I do to show only the Activities that has Members attached to it?
I think that in the NSPredicate I have to do some count so that only the Activities with count > 0 are returned. Is that so?
How?
(i'm newbie in coredata...)
Thanks,
RL
You need to add a subquery to your predicate acting on the CompanyActivity entity as follows:
[[NSPredicate predicateWithFormat:#"deleted == %#" && (0 >= SUBQUERY(Members, $sub, $sub.deleted == %#).#count)", [NSNumber numberWithBool:NO] [NSNumber numberWithBool:NO]];
The first part of the predicate returns objects which have not been deleted, the second one related to the subquery will take care of retrieving all those CompanyActivity objects whose Members have not been deleted.

Resources