如何在 iOS 应用程序中从 CoreData 的实体获取属性名称

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

我正在使用以下代码从 CoreData 读取数据,但我们可以将第一个属性名称 "firstName"、"lastName"、"age" 从 CoreData 读取到数组中并读取它们的值,而不是在代码中写入所有名称。

这是重复的工作,因为它们也是用 DataModel 编写的。

 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)")
    }
}

试试这个,从 NSManagedObject

访问您的实体名称

例如

  • 对于AppDelegate.SharedInstance(),只需在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
      }
 }


使用 Xcode 为您生成的与实体名称同名的 class

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)")
    }
}