Search code examples
objective-cmacoscocoacore-datansfetchrequest

core data fetch request does not return distinct results


I'm trying to return distinct results from a core-data entity to then put into a popup menu. I only want entity with the requested property to appear in the returned dictionary one time so that it could then be used as a predicate for another popup.

e.g. records:

name | id

Test1 | 111

Test1 | 222

Test2 | 333

would return Test1 Test2

So this could be set as a predicate for a NSPopUpButton for name. When the user selects that name it would set a second popup with a content set of corresponding values.

e.g. Name popup with Test1 as selected object yields ID popup with a content set of 111 and 222


So I started with this fetch request, based on articles I read here on SO.

-(void)fetchItems {

        NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Equipment"];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Equipment" inManagedObjectContext:[[NSApp delegate] managedObjectContext]];

        fetchRequest.entity = entity;

        fetchRequest.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"item"]];
        fetchRequest.resultType = NSDictionaryResultType;
        [fetchRequest setReturnsDistinctResults:YES];

        NSArray *dictionaries = [[[NSApp delegate] managedObjectContext] executeFetchRequest:fetchRequest error:nil];
        NSLog (@"names: %@",dictionaries);
}

However the NSLog still returns Nondistinct records! This is the log:

names: (
    {
    item = item2;
},
    {
    item = item1;
},
    {
    item = item1;
}
)

Does anyone have any ideas as to why this fetch isn't executing properly? Also, based on what I have explained that I want to do, am I on the right track with the logic? Thanks


Solution

  • Use the collection object NSSet...

    Following this line in your fetchItems method:

    NSArray *dictionaries = [[[NSApp delegate] managedObjectContext] executeFetchRequest:fetchRequest error:nil];
    

    Add this line:

    NSSet *setDictionaries = [NSSet setWithArray:dictionaries];
    

    Change your log:

    NSLog (@"names: %@",setDictionaries);
    

    Refer to Apple Documentation.

    Also helpful About Collections