简体   繁体   中英

Swift: detecting an unexpected nil value in a non-optional at runtime: casting as optional fails

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: Xcode屏幕抓取

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")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM