【发布时间】:2016-09-16 11:23:38
【问题描述】:
我正在尝试从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 个字符串的设置(名称、desc、lat、long)
有人知道我在这里做错了什么吗?
亲切的问候,
约翰
【问题讨论】:
-
核心数据中
lat的类型? -
类型是字符串。但我认为这是不正确的
-
那个缩进虽然... o.0
-
你的意思是你的CoreData实体包含四个字符串属性吗?如果是这样,请检查 pokemanLat 和 pokemanLon,您到达那里的类型是什么?
-
是的,字符串是所有属性的属性。我想我得到了一本字典,因为我将变量转换为 NSDictionary