我正在运行应用程序,出于某种原因,当我尝试访问数据以将其映射出来时,我收到错误 sudo gem install cocoapods-deintegrate cocoapods-clean
致命错误:在解包可选值时意外发现nil
和
线程1:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)在以下行
let locations = run.locations
如果我将其更改为
let locations = run?.locations
我得到了"否则{"应用程序中的消息,但它没有崩溃。
我知道数据存在,因为我与Liya证实了这一点。不知道为什么我的应用程序没有看到它。
继承代码的其余部分
var run : Run!
func loadMap() {
guard
let locations = run.locations,
locations.count > 0,
let region = mapRegion()
else {
let alert = UIAlertController(title: "Error",
message: "Sorry, this run has no locations saved",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel))
present(alert, animated: true)
return
}
print("loadMap")
mapView.setRegion(region, animated: true)
mapView.add(polyLine())
}
TIA
答案 0 :(得分:0)
布埃诺!谢谢。
好。所以这是
删除
var run : Run!
声明了一个空数组,因为fetch返回[Any]
var locations : [Any] = []
添加代理
let appDelegate = UIApplication.shared.delegate as? AppDelegate
然后将获取数据func写为带有完成处理程序的扩展
extension MapsViewController {
func fetch(completion: (_ complete: Bool) -> ()) {
guard let managedContext = appDelegate?.persistentContainer.viewContext else { return }
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Location")
do{
locations = try managedContext.fetch(fetchRequest) //Trys to call CoreData and returns an Array of type [Any] and assigns them to the array of locations
print("fetched data")
completion(true)
} catch {
debugPrint("could not fetch: \(error.localizedDescription)")
completion(false)
}
}