Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to fetch only selected property in a Core Data query

I have (I guess) typical problem. My Core Data database contains table, which have BLOB fields and quite long text fields.

Usually I do not need to load agrresivly those large size fields. Since there are several thousand records in a database I would prefer to fetch only data I truly need. In other words I would like to make "SELECT name, id FROM TAB_NAME" query, not "SELECT * FROM TAB_NAME" query.

Is there any way to fetch only selected fields using Core Data? Or shall I look for some other option, like, for instance, seperate large fields to another table? Maybe there is a better (easier) way to do this?

I am used to working with Hibernate or JPA, where it easy to do described above operation, after going through Core Data docs I do not see such option.

like image 638
Piotr Kochański Avatar asked Jun 07 '11 07:06

Piotr Kochański


3 Answers

In other words I would like to make "SELECT name, id FROM TAB_NAME" query, not "SELECT * FROM TAB_NAME" query.

The answer to this question was accepted, but FYI, here's how to fetch only specific properties of an entity with Core Data, without re-factoring your model:

// build your NSFetchRequest
// ...

[request setResultType:NSDictionaryResultType];
[request setPropertiesToFetch:
  [NSArray arrayWithObjects:@"property1", @"property2", /* etc. */ nil]];    

See also the documentation for NSFetchRequest.

like image 111
octy Avatar answered Nov 07 '22 12:11

octy


I think in this case you might want to keep the larger fields (the ones you'd rather not load) on a separate entity, and just create a 1:1 relationship for that. That way, even if you fault your object, you'll only be fetching the "lighter" attributes, and to fetch the heavier ones you'd use the relationship.

like image 39
André Morujão Avatar answered Nov 07 '22 13:11

André Morujão


Core Data already does "lazy loading" in the form of faulting: faults only pull data from the store when you need it, which reduces memory and performance overhead. Also read the Core Data Performance documentation for more information:

A BLOB often represents an attribute of an entity—for example, a photograph might be an attribute of an Employee entity. For small to modest sized BLOBs (and CLOBs), you should create a separate entity for the data and create a to-one relationship in place of the attribute. For example, you might create Employee and Photograph entities with a one-to-one relationship between them, where the relationship from Employee to Photograph replaces the Employee's photograph attribute. This pattern maximizes the benefits of object faulting (see “Faulting and Uniquing”). Any given photograph is only retrieved if it is actually needed (if the relationship is traversed).

like image 5
Alex Reynolds Avatar answered Nov 07 '22 12:11

Alex Reynolds