我有一个 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:
同样的问题和解决方案也提到了 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/