Marcin Kuptel
Marcin Kuptel

Reputation: 2664

How to fetch specific properties of a related entity?

In my app I have two entities: Deal and Address. They are connected via a many-to-many relationship. The Address entity has many properties - latitude and longitude are two of them. Is it possible to fetch all the Deal objects together with their related Address objects so that only certain properties of the Address objects are retrieved (latitude and longitude)?

Upvotes: 0

Views: 209

Answers (1)

Mundi
Mundi

Reputation: 80271

If I understand correctly, you do not want to filter the results of your fetch. You want all deals and then just a subset of the attributes of the associated addresses.

It is not clear from your question how you want to use those results. Do the attributes of the Address entity still have to be associated to the respective Deal entities?

If not, you could simply fetch all Address entities and just get the properties you want. Because Core Data will help you manage memory by only fetching the attributes needed you could simply fetch the entire objects. An array of an attribute for all instances can then be easily generated as follows:

[allAddresses valueForKeyPath:@"attributeName"];

You could also directly set the fetch request's resultType property to NSDictionaryResultType and specify the properties in propertiesToFetch.

The other scenario is that you do not want the relationship between the deals and addresses broken. In this case, just fetch all deals (Core Data will use faulting to reduce the memory footprint). You can then iterate through your results and get each attribute easily.

for (Deal *deal in allDeals) {
   NSSet *allLongitudesInAddresses = 
             [deal.addresses valueForKeyPath:@"longitude"];
   // do something with the attributes
}

Upvotes: 1

Related Questions