Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch distinct values in Core Data?

So in looking through Core Data Snippets, I found the following code:

...
[request setEntity:entity]; 
[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctValues:YES];
[request setPropertiesToFetch:[NSArray arrayWithObject:@"<#Attribute name#>"]];

// Execute the fetch
NSError *error;
id requestedValue = nil; // WTF? This isn't defined or used anywhere
NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
if (objects == nil) {
     // handle the error
}

This is great and seems perfect for what I need...but how does one actually use it? I assume since it's returning dictionaries, I need a key to get at the values - but where's the key defined? Is that the "id requestedValue = nil" line? If so, how does "requestedValue" become the key? Xcode gives me a compiler warning about an unused variable at the "requestedValue" declaration. I feel like I'm missing something here.

Thanks in advance for any assistance you can offer.

like image 390
Andy Avatar asked May 07 '10 02:05

Andy


1 Answers

requestedValue is nothing and is obviously not being used (perhaps it was part of some other example that got cut&paste into this example code--who knows). You can just ignore it.

The keys for the dictionary are the same as the attributes you fetched and are defined in your model. So, for example, if you had a person entity with three attributes defined, name, age, phoneNumber, and you requested only name, that would be the only keys with data in your dictionaries. So:

[request setEntity:entity]; 
[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctResults:YES];
[request setPropertiesToFetch:[NSArray arrayWithObject:@"name"]];

// Execute the fetch
NSError *error;
NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
if (objects == nil) {
     abort();
}
for( NSDictionary* obj in objects ) {
  NSLog(@"Person: %@", [obj objectForKey:@"name"]);
}
// ...

So, if you have 5 people in your data store named Bob, Sally, Joe, Freida and Sue, you would see those names print out. If you want to use any of the other attributes (like their age), you would have to add that to the array you set in setPropertiesToFetch:.

In most cases, it is probably best to simply retrieve the managed object, however. The object will be faulted so you won't even bring attributes into memory unless you actually access them. Plus, if you want to make changes to the objects, you could and persist them to the store (with managed objects).

like image 152
Jason Coco Avatar answered Oct 18 '22 00:10

Jason Coco