Swift 3 - Nsfetchrequest Distinct Results

CoreData get distinct values of Attribute

You should use the backing store to help you get distinct records.

If you want to get an array with just John, Betty, Edward here's how you do it:

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"MyEntity"];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:self.managedObjectContext];

// Required! Unless you set the resultType to NSDictionaryResultType, distinct can't work.
// All objects in the backing store are implicitly distinct, but two dictionaries can be duplicates.
// Since you only want distinct names, only ask for the 'name' property.
fetchRequest.resultType = NSDictionaryResultType;
fetchRequest.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"name"]];
fetchRequest.returnsDistinctResults = YES;

// Now it should yield an NSArray of distinct values in dictionaries.
NSArray *dictionaries = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
NSLog (@"names: %@",dictionaries);

Swift Core Data - Request with distinct results

You need to set

request.resultType = NSFetchRequestResultType.DictionaryResultType

It returns dictionaries, but the distinct filter should work.

If you do not want to go down that route, filter in memory (also recommended). Do a normal fetch and then

let distinct = NSSet(array: results.valueForKeyPath("docID") as [String])

With Swift 2.0 I prefer

let distinct = NSSet(array: results.map { $0.docID })

NSFetchRequest: Query for distinct values and count other properties values

The correct answer to this question to refactor the data model in order to avoid redundancy.

The country strings are repeated unnecessarily in the table. Additionally, you make a simple query gratuitously complicated. The model should reflect your data, and writing out "USA" for every American city is just not smart or efficient.

Your data model should look like this

Country <----->> City

Now you can just fetch all countries and get the cities with cities.count.

Swift 3. NSFetchRequest propertiesToFetch

I forgot to set resultType for NSFetchRequest.

let fetchRequest = NSFetchRequest<MyClass>(entityName: "MyClass")
fetchRequest.propertiesToFetch = ["myAttributeName"]
fetchRequest.resultType = .dictionaryResultType


Related Topics



Leave a reply



Submit