核心数据 - 由于未捕获的异常终止应用程序' NSUnknownKeyException'

时间:2017-02-08 13:14:13

标签: ios swift

我试图在iOS中使用swift来检索我的xcdatamodel的数据元素  文件

看看:

@IBAction func sees(_ sender: Any) {
    let appdel = UIApplication.shared.delegate as! AppDelegate
    let contect:NSManagedObjectContext = appdel.persistentContainer.viewContext
    var results = NSManagedObject()
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Places")
    let records = try! contect.execute(fetchRequest)
    let getlatitude = records.value(forKey: "lat")
    let getlongitude = records.value(forKey: "long")
    print("getted: \(getlatitude) \(getlongitude)")
}

如何查看我的xcdatamodel文件

enter image description here

我遇到了崩溃:

  

2017-02-08 14:10:21.330293 Parkar [6398:1283817] [LogMessageLogging]   6.1无法检索CarrierName。 CTError:domain-2,code-5,errStr:((os / kern)失败)2017-02-08 14:10:24.404130   Parkar [6398:1283769] [错误]错误:CoreData:错误:无法呼叫   NSManagedObject类上指定的初始化程序&#39; NSManagedObject&#39;   CoreData:错误:CoreData:错误:无法调用指定的   NSManagedObject类上的初始化程序&#39; NSManagedObject&#39;

     

2017-02-08 14:10:24.410434 Parkar [6398:1283769] ***终止应用   由于未被捕获的异常&#39; NSUnknownKeyException&#39;,原因:   &#39; [valueForUndefinedKey:]:这个   class不是键值lat的密钥值编码。&#39;

2 个答案:

答案 0 :(得分:0)

试试此代码,它对我有用

  let fetch = NSFetchRequest<NSFetchRequestResult>()
        // Create Entity Description
        let entityDescription = NSEntityDescription.entity(forEntityName: "Places", in: self.managedObjectContext)

        // Configure Fetch Request
        fetch.entity = entityDescription

        do {
            let result = try self.managedObjectContext.fetch(fetch)
            var orderList :NSArray  = result
             let lat = orderList.value(forKey: "lat") as! String
              let long = orderList.value(forKey: "long") as! String

        } catch {
            let fetchError = error as NSError
            print(fetchError)
           }

答案 1 :(得分:0)

这是我设法组建的一个有效的解决方案:

/** @var ProductRepository $repository */
$repository = $this->getDoctrine()->getRepository('AppBundle:Product');
$queryBuilder = $repository->createQueryBuilder('p');

首先,我将let appdel = UIApplication.shared.delegate as! AppDelegate let context:NSManagedObjectContext = appdel.persistentContainer.viewContext var results = NSManagedObject() //not sure what this is used for let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Places") do { let records = try context.fetch(fetchRequest) as! [Places] let placeObject = records[0] let lat = placeObject.lat let long = placeObject.long print("\(lat) \(long)") } catch { print(error.localizedDescription) } 更改为正确的字contect。接下来,我们必须使用context包围我们的try语句以捕获任何错误。然后我将catch变量从您的Core Data中的实体转换为records数组。现在,您可以访问Places实体中的属性,例如Placeslat