首页 > 解决方案 > 此类不符合键 Project1 的键值编码。

问题描述

我是iOS开发的新手,你能帮我解决你的错误吗?谢谢你提前。

未捕获的异常“NSUnknownKeyException”,原因:“[setValue:forUndefinedKey:]:此类不符合键 Project1 的键值编码。”

 let  context  = appdelegate.persistentContainer.viewContext
 let proj = Project() 
        let arrProj = dic.object(forKey: "Projects") as! NSArray
        for n in 0..<arrProj.count {
            let subDic = arrProj.object(at: n) as! NSDictionary
            let item = ProjectItem(dict: subDic)
            proj.arrProjs.append( item )


           let projects = NSEntityDescription.entity(forEntityName: "Projects", in: context)
            projects?.setValue(item.Project, forKey: "project1")
            projects?.setValue(item.Project2, forKey: "project2")
            projects?.setValue(item.ID, forKey: "projectid")
            projects?.setValue(item.radius, forKey: "radius")
            projects?.setValue(item.GeofenceType, forKey: "geo_Type")
            projects?.setValue(item.Geofence, forKey: "geofence")
            projects?.setValue(item.Coordinates, forKey: "coordinates")
        }

标签: swiftcore-data

解决方案


您应该在对象中设置值NSManagedObject,而不是在NSEntityDescription对象中

let entity = NSEntityDescription.entity(forEntityName: "Projects", in: context)
for n in 0..<arrProj.count {
    let projects = NSManagedObject(entity: entity!, insertInto: context)
    projects?.setValue(item.Project, forKey: "project1")
    projects?.setValue(item.Project2, forKey: "project2")
    //...
}

推荐阅读