Home > Net >  How can you get attribute names from an Entity from CoreData at an iOS app
How can you get attribute names from an Entity from CoreData at an iOS app

Time:01-07

I am reading data with following code from CoreData but instead of that can we read first attribute names "firstName", "lastName", "age" from CoreData into an array and read their values instead of writing all the names in code.

It is repeated work because they are written in DataModel as well.

 loadData()  {
    
   let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Entity")
 
    
        do {
            let result = try context.fetch(fetchRequest)
            dump(result)
            for data in result as! [NSManagedObject] {
                
                fNames = data.value(forKey: "firstName") as! String
                lNames = data.value(forKey: "lastName") as! String
                age = data.value(forKey: "age") as! Int
                
                print("first \(fNames),  last : \(lNames),  last : \(age)")
            }
        } catch {

        print("Could not load data: \(error.localizedDescription)")
    }
}

CodePudding user response:

Try this, access your entity name from NSManagedObject

e.g.

  • For AppDelegate.SharedInstance(), just declare this func in AppDelegate.swift
class func sharedInstance() -> AppDelegate
{
        return UIApplication.shared.delegate as! AppDelegate
}
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"CallHistory") //Here CallHistory is my entity name which i can access as NSManagedObject
  
let arr_callhistory = try AppDelegate.sharedInstance().persistentContainer.viewContext.fetch(fetchRequest) as! [CallHistory]

 if arr_callhistory.count != 0
   {
      for callhistory_dict in arr_callhistory
      {
           let callStatus = callhistory_dict.callStatus
      }
 }


CodePudding user response:

Use the class that Xcode has generated for you that has the same name as the entity name

loadData()  {    
    //Declare fetch request to hold the class you want to fetch
    let fetchRequest = NSFetchRequest<Entity>(entityName: "Entity")

    do {
        let result = try context.fetch(fetchRequest)
        dump(result)
        for data in result {     
            // result is now [Entity] so you can access properties directly
           //  and without casting           
            let firstName = data.firstName
            let lastName = data.lastName
            let age = data.age
            
            print("first \(firstName),  last : \(lastName),  age : \(age)")
        }
    } catch let error as NSError {
        print("Could not load data: \(error.localizedDescription)")
    }
}
  •  Tags:  
  • Related