Passing Realm object/fields between view controllers


(Brent Worley) #1

Here’s my setup:

VC 1 - TableViewController divided into sections. Attempting to pass the object exist underneath the cell to another VC.

VC 2 - An add/edit item VC. Goal is to get data from VC 1, populate it in the form, and allow the user to edit, which will save back and update VC 1 on dismiss.

The issue is when I attempt to pass the object across VC’s, and I go to populate the UITextField of the add/edit form, I get “Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value: file”

VC 1’s prepare/perform (note: itemAtCell is a property defined as an individual object, not a results set):

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        itemAtCell = itemsList.filter("item_category = '\(categories[indexPath.section])'")[indexPath.row]
        performSegue(withIdentifier: "updateItemSegue", sender: self)
    }
    
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let destinationVC = segue.destination as! AddItemView
        
        destinationVC.delegate = self
        if segue.identifier == "updateItemSegue" {
            print("here")
            print("Item at cell item name = \(itemAtCell.item_name)")
            destinationVC.itemAtCell = itemAtCell
        }
        else if segue.identifier == "addItemSegue" {
            destinationVC.listID = list_id
        }
    }

VC 2 receiving:

var itemAtCell : Items? {
        didSet {
            itemText.text! = itemAtCell!.item_name
            itemCat.text! = itemAtCell!.item_category
            itemQuantity.text! = itemAtCell!.item_quantity
            listID = itemAtCell!.list_id
        }
    }

When I check values via the print() statements, data is in the object. However, when passing it across is when I get the error. I’m not sure why the object is getting a nil when passing to the second VC.


(Brent Worley) #2

Found my answer eventually.

The issue is not the Realm object being nil but rather the other fields. I moved the code for didSet into viewDidLoad() and set that way.

Answering my own thread in case this helps others.