Nosrettap
Nosrettap

Reputation: 11320

How to fetch an array of attributes in iOS Core Data?

I'm using CoreData (NSManagedObject, UIManagedDocument) for an iOS app and I was wondering if it is possible to fetch an array of attributes.

For example, suppose I have Person entities in my database and each Person has an attribute called income and a name called name. Suppose I have multiple Persons in my database. Is it possible to fetch an array containing all of the incomes for my entire database? (An array with each person's income as an entry). If so, how would I sort the array by their name?

If this is not possible, how would you suggest I go about accomplishing this? I don't want to fetch the entire Person entity because there are many other large attributes such as images which would take a long time to fetch.

Upvotes: 1

Views: 1187

Answers (1)

You can fetch the properties you want this way:

NSFetchRequest* fetchRequest = [NSFetchRequest new];
fetchRequest.entity = <person entity description>;
fetchRequest.propertiesToFetch = @[ @"name", @"income" ];
fetchRequest.sortDescriptors = @[ [NSSortDescriptor sortDescriptorWithKey: @"name" ascending: YES] ];
fetchRequest.resultType = NSDictionaryResultType;

NSError* error = nil;
NSArray* personsAttributes = [managedObjectContext executeFetchRequest: fetchRequest error: &error];

personsAttributes will look like that:

[
    { "name" : "Alfred", "income" : 1000 },
    { "name" : "Birgite", "income" : 2000 },
    …
]

Code with ARC & literals. You'll may have to tailor it to your needs and compilation options.

Upvotes: 2

Related Questions