9

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.

XJones
  • 21,959
  • 10
  • 67
  • 82

1 Answers1

13

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.

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
  • cool, didn't realize `valueForKey` walked the array for you. wouldn't that would work on the array of managed objects as well? – XJones Nov 18 '11 at 21:06
  • @XJones: I imagine so, yes, but if you just want to extract a property, then it's almost certainly simpler/more efficient to grab dictionaries instead of full managed objects. – Lily Ballard Nov 18 '11 at 21:36
  • perhaps, though not sure why. I'm already restricting my request to just the property I care about. in terms of performance (speed & memory footprint) don't know if NSDictionary vs NSManagedObject will make any significant difference here. In any case, thanks for your help! – XJones Nov 18 '11 at 21:44
  • I was hoping there was a way to have the fetch request itself return the array of values but I don't think that's possible. Using `valueForKey:` with an array is a nice optimization, if nothing else I let the framework walk the array for me. +1 and accept (unless an answer appears that directly returns the array of values from the fetch request). thanks again. – XJones Nov 18 '11 at 21:47