Gytis
Gytis

Reputation: 670

Core Data: object in a predicate

In my core data object model I have 3 entities with appropriate relationships so that MyObject can have many MyObjectProperties, and each property can have one MyObjectPropertyImage.

Given a myObject I want to fetch all the images.

I try to do it using the following predicate, however I get an empty array:

[NSEntityDescription entityForName:@"MyObjectPropertyImage" inManagedObjectContext:managedObjectContext];
[NSPredicate predicateWithFormat:@"ANY myObjectProperty.myObject == %@", myObject];

Any ideas?

Upvotes: 1

Views: 1046

Answers (2)

TechZen
TechZen

Reputation: 64428

Since you have a MyObject instance in hand and it has the relationship path of myObjectProperties-->ObjectProperty-->>PropertyImages you just need to traverse the relationships. It's easy to do this with valueForKeyPath:

Thusly:

NSArray *images=[myObjectInstances valueForKeyPath:@"myObjectProperties.propertyImage"];

(Note: I might have your attribute names wrong but you can get the idea.)

As general rule, you never fetch when have an object from the graph available. You fetch to "pick out thread" of objects matching the predicate and then to find all related objects you follow the thread/relationships to the related objects.

Upvotes: 0

octy
octy

Reputation: 6545

When working with Core Data it's best to think of your entities as just that: entities in an object graph, instead of tables in a database. Therefore, you don't need to fetch entities related to others using a predicate. Instead, navigate the object graph using the relationships defined in the model. To get all the images related to myObject:

// assuming the relationships are called 'myObjectProperties' and 'myObjectPropertyImage', respectively
NSSet *allImages = [myObject.myObjectProperties valueForKey:@"myObjectPropertyImage"];

Note that this may trigger additional trips to the database if your object graph is not loaded in memory for your myObject entity. To avoid that, make sure you set the pre-fetching relationship keypaths in your fetch request for myObject.

I hope this helps...

Upvotes: 2

Related Questions