0

I'm new to Swift, and was thrilled to find that we no longer need delegates and protocols to send a chunk of data to another view controller.

However, using this code:

...

class DetailTableViewController: UITableViewController {
    var detailPicPath: String?

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let detailPredicate = NSPredicate(format: "account = %@", currentAccount)
    let transactions = realm.objects(Transaction.self).filter(detailPredicate)
    let orderedTransactions = transactions.sorted(byKeyPath: "transDate", ascending: false)
    let item = orderedTransactions[indexPath.row]
    detailPicPath = item.picPath

    self.performSegue(withIdentifier: "microSegue", sender: indexPath.row)
}

and this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "microSegue" {
        let destination: MicroDetailViewController = segue.destination as! MicroDetailViewController
        destination.picPathForThisTrans = detailPicPath

}

I get nil in destination.picPathForThisTrans, and a crash with this warning:

Fatal error: Unexpectedly found nil while unwrapping an Optional value

at the point where picPathForThisTrans is called in the destination view controller.

I've searched SO and Google (which usually leads back to SO) but haven't found a solution. I'm wondering if I'm defining my vars correctly.

Could sure use some guidance!

TIA

Edit

Upon reading the post referenced below by @rmaddy, I revisited my issue and discovered that the problem was not with the saving of properties nor how they were unwrapped. While these are issues with which I certainly need more experience, the problem was caused by a more fundamental oversight--I was using both a Storyboard segue, and one called in code. In the storyboard segue, prepareForSegue wasn't in possession of the relevant information. Since it was apparently called after the programmatic method, it overwrote the data in the receiver, resulting in nil at the critical point.

I discovered this issue when I found (using a whole bunch of print() statements) that prepareForSegue was being called twice, once when it was loaded, and once unloaded.

Doing some further research, I found this post, which enabled me to fix the issue. Many thanks to @rmaddy and to those who contributed to the post mentioned relating to segues!

rattletrap99
  • 1,469
  • 2
  • 17
  • 36

0 Answers0