我无法用自己来解决这个问题 . 我正在检索存储在Core Data中的一些设置,并将这些设置打印到一些UITextFields . 这在同一个项目中的另一个VC中运行良好,但在这里我得到“在解开可选值时意外地发现nil” .
我XCode我可以看到值存在吗?为什么我会这次崩溃?请参阅附件截图 .
这是我现在的代码 . 在XCode中仍然是相同的错误消息
func getSettingsFromCoreData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "DeathMatchSettings")
do{
let results = try context.fetch(request)
let managedObject = results as! [NSManagedObject]
let getDMSettings = managedObject[0]
guard let playerOne = getDMSettings.value(forKey: "playerOne") else {
return
}
print(playerOne)
txtPlayerOne.text = String(describing: playerOne)
}catch{
fatalError("Error in retreiving settings from CoreData")
}
}
2 回答
您还可以使用guard语句来解包您的可选变量 . 仅当您确信变量具有非可选值时,才最好使用强制解包 .
Player1
可以是 nil . 你试图将它变成一个值,但它在swift中是一个致命的错误 . 使用if let
语句来测试值:在docs中阅读有关 type casting 的更多信息:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html