1

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.