John Stupak
John Stupak

Reputation: 31

Unique Values from Core Data

I have a core data-based app that manages records of auto dealerships. Each record stores the dealer's address, which is broken into addressLine1, addressLine2, city, state, and zip components, each stored as a string in the data store.

I would like to present a list of cities with dealerships to the user, so I'm trying to figure out if it is possible to get a list of every unique city name that has been entered into the store. I other words, is it possible to issue some sort of query against all of the dealership records that will return a list of distinct city names?

I would know how to do this easily with a SQL query, but (how) is this done in Core Data?

Thanks very much!

Upvotes: 3

Views: 4012

Answers (3)

palaniraja
palaniraja

Reputation: 10492

Core Data have the option to get distinct record. The method of getting unique results using NSArray and NSSets are not recommend.

[fetchRequest setResultType:NSDictionaryResultType];
NSDictionary *entityProperties = [entity propertiesByName];
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObject:[entityProperties objectForKey:@"<<yourattrib>"]]];
[fetchRequest setReturnsDistinctResults:YES];

Refer Apple documentation and check the answers for How to fetch distinct values in Core Data?

Upvotes: 7

user189804
user189804

Reputation:

A quick way to ensure a unique set of things is to use NSSet. Once you have the results for a query on city take your NSArray and do

NSSet* uniqueResults = [NSSet setWithArray:resultsArray];

You can transform the set into another collection class if more convenient or just the object enumerator to do something with all of them. I do not know if this approach or the valueForKeyPath method from Dave DeLong is more efficient.

Upvotes: 0

Dave DeLong
Dave DeLong

Reputation: 243146

You're right, there isn't an "easy" way to do this with Core Data, because Core Data is not a database. However, it is possible. Here's the general idea:

  1. Fetch all your Dealer objects via an NSFetchRequest. To simplify the query, you can set the fetch request to only fetch the city attribute.
  2. Execute NSArray * uniqueCities = [fetchedDealers valueForKeyPath:@"@distinctUnionOfObjects.city"];

Upvotes: 5

Related Questions