[英]Store location in CoreData (Swift)
我试图弄清楚如何从JSON
在CoreData
存储位置。 我正在使用此代码从JSON
API获取数据并将其存储在CoreData
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let newPok = NSEntityDescription.insertNewObject(forEntityName: "Person", into: context)
for jsonItem in json {
let item = jsonItem as! NSDictionary
let pokemonName = item["name"]
let pokemonDesc = item["description"]
let pokemonLat = (item["location"] as! NSDictionary) ["latitude"]
let pokemonLon = (item["location"] as! NSDictionary) ["longitude"]
let coordinates = CLLocationCoordinate2D(latitude: pokemonLat as! CLLocationDegrees, longitude: pokemonLon as! CLLocationDegrees)
let annotation = MKPointAnnotation()
annotation.title = pokemonName as! String?
annotation.subtitle = pokemonDesc as! String?
annotation.coordinate = coordinates
self.map.addAnnotation(annotation)
newPok.setValue(pokemonName as! String, forKey: "name")
newPok.setValue(pokemonDesc as! String, forKey: "desc")
newPok.setValue(pokemonLat as! String, forKey: "lat")
newPok.setValue(pokemonLon as! String, forKey: "lon")
do {
try context.save()
} catch {
print("not saved")
}
}
但是,当我运行这段代码时,总是会遇到fatal exception
。
error Domain=NSCocoaErrorDomain Code=134190 "(null)" UserInfo={entity=Person, property=lat, reason=Source and destination attribute types are incompatible}
我的数据库有一个包含4个字符串的设置(名称,描述,纬度,长度)
有人知道我在这里做错什么吗?
亲切的问候,
约翰
您需要将纬度和经度属性的数据类型从String
更改为Integer16
好吧,我知道了。
我将核心数据属性从string
更改为double
pokemonLat as! Double?
并在代码pokemonLat as! Double?
pokemonLat as! Double?
。 那行得通。
感谢您的帮助! 涂上它!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.