Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an efficient way to get an array of property values from a core data entity?

Consider the following:

NSFetchRequest *request = [[NSFetchRequest Alloc] init];
request.entity = [NSEntityDescription entityWithName:@"Person" inContext:_MOC];
request.propertiesToFetch = [NSArray arrayWithObject:@"Name"];
NSError *error = nil;
NSArray *results = [_MOC executeFetchRequest:request error:&error];

This returns an array of Person objects. What I want is an array of Person.name values from those objects. Currently I walk the results array, extract the names and build a new array. Is there a cleaner, faster way to do this? I've thought about changing request.resultType to NSDictionaryResultType but that doesn't buy much as I still need to transform the array of dictionary into the array I need.

I already have the solution above implemented, so really looking for a better way. If the correct answer is "there is no better way" that's fine, just making sure I'm not missing something. Thanks!

EDIT: while thinking about this, I'm questioning my need for an array of values vs. just using the array of managed objects. In any case, would still appreciate a great answer if there's one out there.

like image 529
XJones Avatar asked Nov 18 '11 20:11

XJones


1 Answers

Ask for NSDictionaryResultType, and then with the resulting array of dictionaries, just ask for [array valueForKey:@"name"]. When an NSArray receives -valueForKey: it returns a new NSArray created from the results of calling -valueForKey: on all its elements.

like image 193
Lily Ballard Avatar answered Nov 07 '22 23:11

Lily Ballard