Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
647 views
in Technique[技术] by (71.8m points)

core data - 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 screen grab

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...