ios - 在 CoreData 中存储位置 (Swift)

标签 ios json swift core-data

我正在尝试弄清楚如何从 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")
    }
}

但是当我运行此代码时,我总是遇到致命异常

error Domain=NSCocoaErrorDomain Code=134190 "(null)" UserInfo={entity=Person, property=lat, reason=Source and destination attribute types are incompatible}

我的数据库设置有 4 个字符串(名称、描述、纬度、长)

有人知道我在这里做错了什么吗?

亲切的问候,

约翰

最佳答案

您需要将纬度和经度属性的数据类型从String更改为Integer16

关于ios - 在 CoreData 中存储位置 (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39530292/

相关文章:

ios - ARKit图像识别——图像跟踪

ios - 如何检测 child Sprite 的触摸

ios - 如何使用多对等连接框架在两部 iPhone 之间流式传输音频文件?

ios - 将函数转换为扩展时遇到问题

javascript - 客户端接收json对象到javascript

jquery - 将Grails从1.3.4升级到2.0.3后,将数据呈现为JSON无法正常工作

iphone - 为什么 __NSCFDictionary 不是一种 NSDictionary 类

swift - NSUserDefaults 上的属性观察者

json - 尝试利用 decodable

ios - 在AVAudioPlayer中停止声音并显示AQDefaultDevice(173):跳过输入流错误日志