How to fetch only one column Data in Core Data using swift 3

Viewed 4187

I am new in CoreData and I am trying to fetch only one column Data. I am trying using below code:

//MARK :- Fetch All Calculation
func fetchUniqueParentAxis(testID : String) -> [String]  {

    var arrAxis : [String] = []

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "TesCalculation")
    fetchRequest.predicate = NSPredicate(format: "testID == %@ ",testID)
    fetchRequest.includesPropertyValues = true
    fetchRequest.returnsObjectsAsFaults = false
    fetchRequest.propertiesToFetch = ["parentAxis"]

    do {
         calculation = try AppDelegate.getContext().fetch(fetchRequest) as! [TesCalculation]//try AppDelegate.getContext().fetch(fetchRequest) as! [String : AnyObject]
    }

    catch let error {
        //Handle Error
        Helper.sharedInstance.Print(error as AnyObject)
    }
 }. 

"parentAxis" is my a column and I want to fetch data of that column only .

2 Answers

You can absolutely fetch a subset of columns in CoreData. Yes, I agree Core Data IS an Object Graph solution that can use SQLite as a storage engine. However, fetching a subset of data instead of an entire NSManagedObject has been possible to do for a very long time in CoreData but recent changes have made it slightly different than before.

let fetchRequest = NSFetchRequest<NSDictionary>(entityName: TesCalculation.entity().name!)
fetchRequest.resultType = .dictionaryResultType
fetchRequest.predicate = NSPredicate(format: "testID == %@ ",testID)
fetchRequest.propertiesToFetch = ["parentAxis"]
do {
    let results = try AppDelegate.getContext().fetch(fetchRequest)
} catch let error as NSError {
    print(error)
}

What this will return you is something that looks like this:

[
   {
      "parentAxis": "abc"
   },
   {
      "parentAxis": "xyz"
   }
]

The question was not about performance gain (even though there might be; I truly have no idea!) but rather if/how this can be done and this is how it can be done. Plus, I disagree with other statements made that it "doesn't make sense to have a property without an object." There are plenty of cases where you are allocating objects where all you need is a property or two for the need. This also comes in handy if you are loosely coupling Entities between multiple stores. Of course there are other methods for this as well (your xcdatamodel's Fetched Properties) so it just really depends on the use case.

Just to show that it has been around for some time this is in the header of the NSFetchRequest under NSFetchRequestResultType:

@available(iOS 3.0, *)
public static var dictionaryResultType: NSFetchRequestResultType { get }
Related