Swift:在运行时检测非可选的意外nil值:转换为可选失败 [英] Swift: detecting an unexpected nil value in a non-optional at runtime: casting as optional fails
问题描述
我有一个 UITableViewController
通过 NSFetchedResultsController
从Core Data加载它的条目。像这样:
let historyItem = fetchedResults.objectAtIndexPath(indexPath)as HistoryItem
historyItem
有一个 title
this:
@NSManaged var title:String
但是不知为什么核心数据在一些条目中具有 title
的nil值,导致EXC_BAD_ACCESS,因为 title
不是 String?
。此问题已在和我以前的重复问题 Swift:处理意外的nil值,当变量不是可选的
但它不适用于我。我使用Xcode 6.2和iOS8。
我误解了什么吗?
$ p我认为如果核心数据可以返回nil的值, p>
@NSManaged var title:String?
无需强制转换即可测试
if let possibleTitle = historyItem.title {
NSLog(possibleTitle is set OK)
} else {
NSLog(possibleTitle is nil)
}
I have a UITableViewController
loading its entries from Core Data via a NSFetchedResultsController
. Like this:
let historyItem = fetchedResults.objectAtIndexPath(indexPath) as HistoryItem
historyItem
has a title
property defined like this:
@NSManaged var title: String
but somehow the core data has a nil value for title
in some entries which causes EXC_BAD_ACCESS because title
is not String?
. This problem has been addressed at Check if property is set in Core Data? and the high-voted answer there suggests something like this:
if let possibleTitle = historyItem.title as String? {
NSLog("possibleTitle was set OK")
} else {
NSLog("possibleTitle was nil")
}
but I just tried that and it still gave me EXC_BAD_ACCESS:
That same problem and solution is also mentioned at Swift - casting a nil core data string as an optional value and my earlier duplicate question Swift: handling an unexpected nil value, when variable is not optional but it doesn't work for me. I'm using Xcode 6.2 and iOS8.
Am I misunderstanding something, please? Should this approach work?
I think you should make your title an optional if core data can return nil value for title
@NSManaged var title: String?
And test it without the cast
if let possibleTitle = historyItem.title{
NSLog("possibleTitle was set OK")
} else {
NSLog("possibleTitle was nil")
}
这篇关于Swift:在运行时检测非可选的意外nil值:转换为可选失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!