This question already has an answer here:
- Check if property is set in Core Data? 2 answers
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!
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 yourNSManagedObject
historyItem class.@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:When I do this in editor I dont get an error so might be the answer: