Parent not seeming to be available for appending


I am trying to collect input from a few UITextfields in a ViewController and assign some of the data as the Parent ( a Category ) and the rest as the next level Child object ( Items ) in the same UIViewController, and without the need for UIAlerts.

In the code below getting the Category ( Parent ) and its Child data ( Items ) assigned is successful. But my difficulty is getting child objects appended to an established parent

more after the jump:

     @IBAction func addButtonPressed(_ sender: CustomButton) {
        let newCategory = Category()
        newCategory.kind = categoryField?.text ?? "-"
            if !categorySet.contains(itemCategorised) {
                do { try self.realm.write
                } catch { 
					print("Error saving category, \(error)") 
            }  // end if
				// 1. everything goes through here
                let thisCategory = Category()
				// 2a. ends up in a set collection
                thisCategory.kind = categoryField?.text ?? "-"
                let theItem = Item()
          = nameField?.text ?? "-"
                theItem.note    = noteField?.text ?? "-"

                do { try self.realm.write
							// 2b.
                       if !categorySet.contains(itemCategorised)
							// 3.
                        } else {
							// 4.
                } catch { print("Error saving items, \(error)")}
  1. the Category (thisCategory) for the established parent is created under the same conditions as the Category that is added to the realm (newCategory) if there is new input.
    In fact the first run of any Category also goes through here. This works.

2a+b. I use an Set Collection after this function to keep adding Parents, and it ignores new additions to the set. In this way checking if the set contains a Parent property works well.

  1. no problem here. A Parent (newCategory) that was added in the earlier realm write, gets appended with its child data (Items).

  2. for some reason thisCategory is not recognised as existing. If I charge thisCategory.items to newCategory.items, it appends to whatever was the last item added.
    it mat be a flaw in my logic or I don’t understand the difference in state between the Parent declarations.

Any ideas ?

Most demo tutorials on the web covering this split the functions between 2 UITableView Controllers and leave it at that, which is not what I’m doing. Close examination of what goes on in their second detail ViewController has led to the above.


thisCategory is not managed by realm, so when you are adding a new object it wont get inserted.

This is not the case with the newCategory, because you added that before :slight_smile: