views:

356

answers:

2

Hi, I'm trying to create an index representing the first letter value of each record in a Core Data store to be used in a table view controller. I'm using a snippet of the code from Apple's documentation. I would simply like to produce an array or dictionary of distinct values as the result. My store already has the character defined within each record object. Questions:

1) I'm having a problem understanding NSDictionaryResultType. Where does the resulting dictionary object get received so that I can assign it's keys to the view controller? The code seems to only return an array.

2) If I include the line containing NSDictionaryResultType, I get no returns.

3) I realize that I could do this in a loop, but I'm hoping this will work.

Thanks!

 NSEntityDescription *entity = [NSEntityDescription  entityForName:@"People" inManagedObjectContext:managedObjectContext];

 NSFetchRequest *request = [[NSFetchRequest alloc] init];
 [request setEntity:entity];

        [request setResultType:NSDictionaryResultType]; // This line causes no no results.

 [request setReturnsDistinctResults:YES];
 [request setPropertiesToFetch :[NSArray arrayWithObject:@"alphabetIndex"]];

 NSError *error;
 NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
+1  A: 
  1. The fetch request will return an array of dictionary objects (as opposed to an array of managed objects). The dictionaries will only contain key value pairs for the properties specified in the fetch request.

  2. Are you sure it is not returning an array of dictionary objects? What error are you seeing?

UPDATE

Your code works exactly as I have descried in 1. If you are not seeing this result, maybe your data model or data is not as you have described (are you sure that "alphabetIndex" is set for every object?).

From the objects array (of dictionaries), simply do this to get the array you want:

NSArray *letters = [objects valueForKey:@"alphabetIndex"];
gerry3
If I add the line containing "setResultType:NSDictionaryResultType" the resulting array *objects, after the fetch, is zero. If I comment the line out, I get 63 objects which represents all of the objects for the entity "People". There is an attribute called "alphabetIndex" which contains the values a-z representing the first letter of the persons name.
b.dot
To make this short, I would like a dictionary or array representing the unique values. If the only people names present were Anston, Franks, Johnson, and Smith, I would create an array with the values "A,F,J,S".
b.dot
Makes sense. Creating that array is very easy as I have shown in an update above.
gerry3
A: 

Thanks gerry3. I figured it out. I had made a change to my core data class and store. I deleted the SQLite file and recompiled.

b.dot