Swift: handling an unexpected nil value, when vari

2019-05-23 08:26发布

This question already has an answer here:

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

So in cellForRowAtIndexPath the code says

cell?.textLabel?.text = historyItem.title

and that should all be fine. title is not an optional and does not need unwrapping.

However, in the past, the stored Core Data has acquired some objects where the value of the title property is nil. They are there stored, waiting to cause errors. If one of these objects is displayed in a cell, I will see a runtime address exception on the above Swift code line, where the address is 0.

For robustness, I need to write code to make sure the stored data delivered to my program does not cause crashes. However, I cannot write

if historyItem.title == nil { } // gives compiler error

because title is not an optional and the compiler will not let me. If I write

let optionalTitle:String? = historyItem.title

I still get a runtime EXC_BAD_ACCESS on that line.

How can I check that title is not erroneously nil?

Thanks!

3条回答
Luminary・发光体
2楼-- · 2019-05-23 08:47

Since you have nil values, the title property should be optional and you should declare it as optional in your core data model and in your NSManagedObject historyItem class.

查看更多
狗以群分
3楼-- · 2019-05-23 09:00

@NSManaged var title: String should be @NSManaged var title: String? if there is possibility for a nil value. Then, you cannot go wrong with optional binding:

if let historyItemTitle = historyItem.title {
  cell?.textLabel?.text = historyItemTitle
} else {
  cell?.textLabel?.text = "Title missing"
}
查看更多
趁早两清
4楼-- · 2019-05-23 09:10

When I do this in editor I dont get an error so might be the answer:

let a = ""

if a as String? == nil {
        println("Nil")
    }
    else {
        println("Not nil")
    }
查看更多
登录 后发表回答