Search code examples
iosobjective-ccocoa-touchios6modalviewcontroller

iOS passing values from two level Modal view controller


I'm trying to make a form that one of the filed takes value from a two level selections' result.

The main progress will something like:

EditViewController ===> CategoryViewController (which embedded inside a NavigationController by storyboard and popped up as a modal view) ===> SubCategoryViewController (Which will be pushed to NavigationController).

Now I have a problem. After user tap to select a value in SubCategoryViewController, I'm supposed to dismiss SubCategoryViewController and return the value to EditViewController. But I don't know exactly how.

Please suggest any solution.

Thank you.

EDIT:

enter image description here


Solution

  • Every one of those view controllers should have a public property for a weak reference to a model object that represents whatever is being edited.

    So every ____ViewController.h file would have:

    @property (weak, nonatomic) CustomItem *item.
    

    in its interface (assuming a strong reference is somewhere in some data store or array of all the items).

    When EditViewController is preparing for the segue to show CategoryViewController modally, it should assign that same reference to CategoryViewController's item property after assigning any data entered in EditViewController's form to item:

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
        //TODO: assign data from controls to item, for example:
        //self.item.title = self.titleField.text;
    
        CategoryViewController *vc = (CategoryViewController *)segue.destinationViewController
        vc.item = self.item; //pass the data model to the next view controller
    }
    

    Likewise for the segue from CategoryViewController to SubCategoryViewController. This ensures that every ViewController is editing the same object in memory. When you dismiss SubCategoryViewController (assuming somewhere in all of this CategoryViewController was already dismissed), viewWillAppear: will be called on EditViewController- there you can refresh any changes made in the modal views to the item property, just like you would when first displaying the view (it's actually the same method that's called):

    - (void)viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];
        self.titleField.text = self.item.title;
        self.categoryLabel.text = self.item.category;
        self.subcategoryLabel.text = self.item.subcategory;
        //etc....
    }