Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data fetch entities with only unique attributes

I have an Entity "Person" with following attributes:

-name
-surname
-age

I created numbers of objects:

(Ben,    Black,    18)
(John,  Smith,    19)
(Ivan,   Borzov,   18)
(Den,   Balan,     20)
(Kent,  Broman,  20)

How to receive array or any other way to build a table with only unique ages [18,19,20]

Please provide answer in Swift.

P.S. Of course I can fetch all objects, and search for unique manually, but I hope for better solution)

Thank you!

like image 800
S.ork Avatar asked Mar 12 '23 08:03

S.ork


1 Answers

You can both propertiesToFetch and returnsDistinctResults properties of NSFetchRequest to get distinct result of ages across all entities.

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSFetchRequest_Class/#//apple_ref/occ/instp/NSFetchRequest/propertiesToFetch

let fetchRequest = NSFetchRequest(entityName: "Person")
fetchRequest.resultType = .DictionaryResultType
fetchRequest.propertiesToFetch = ["age"]
fetchRequest.returnsDistinctResults = true
let result = try! managedObjectContext.executeFetchRequest(fetchRequest)
like image 58
Ahmed Onawale Avatar answered Mar 25 '23 06:03

Ahmed Onawale