[英]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.