Swift:在运行时在非可选中检测到意外的 nil 值:强制转换为可选失败

标签 swift core-data null option-type

我有一个 UITableViewController 通过 NSFetchedResultsController 从 Core Data 加载它的条目。像这样:

let historyItem = fetchedResults.objectAtIndexPath(indexPath) as HistoryItem

historyItem 有一个 title 属性定义如下:

@NSManaged var title: String

但不知何故,核心数据在某些条目中为 title 设置了 nil 值,这会导致 EXC_BAD_ACCESS,因为 title 不是 String?。此问题已在 Check if property is set in Core Data? 得到解决那里的高票答案表明是这样的:

    if let possibleTitle = historyItem.title as String? {
        NSLog("possibleTitle was set OK")
    } else {
        NSLog("possibleTitle was nil")
    }

但我刚刚试过了,它仍然给了我 EXC_BAD_ACCESS: Xcode screen grab

同样的问题和解决方案也提到了 Swift - casting a nil core data string as an optional value和我之前重复的问题 Swift: handling an unexpected nil value, when variable is not optional 但它对我不起作用。我正在使用 Xcode 6.2 和 iOS8。

请问我是不是误会了什么?这种方法应该有效吗?

最佳答案

如果核心数据可以为标题返回零值,我认为你应该让你的标题成为可选的

@NSManaged var title: String?

并在没有强制转换的情况下进行测试

if let possibleTitle = historyItem.title{
    NSLog("possibleTitle was set OK")
} else {
    NSLog("possibleTitle was nil")
}

关于Swift:在运行时在非可选中检测到意外的 nil 值:强制转换为可选失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29031080/

相关文章:

ios - 导航 Controller 未推送另一个 View

core-data - 在 CoreData 中保存 Swift CLLocation

JAVA - 变量始终为空

sql - 当 COUNT(*) 为 NULL 时,在 GROUP BY 中返回 0

ios - 互操作 Async/await、@MainActor 和 DispatchQueue.main.async

swift - PushVIewController 导致解雇不起作用,现在删除导航栏

swift - 仅字典存储一个键和值/覆盖上一个键和值

保存在 Core Data 中的 iOS 数据无法在发布后继续存在

iphone - 有没有人有核心数据中获取属性的工作示例?

sql - 为什么bcp在列包含空字符串时输出null,在列为null时输出空字符串?