0

I have a TableViewController, lets call it A, that is in a container view of another view controller, B. I need A to reload it's data when a value changes in B. I also need it to get this changed value from B. Any ideas?

user3250926
  • 127
  • 1
  • 2
  • 7
  • 1
    You simply need to invoke a method in A from your object B instance. This is basically a delegation pattern. – Paulw11 Aug 22 '15 at 22:12

1 Answers1

1

Have you considered using notifications?

So, in B – I would do something like:

// ViewControllerB.swift

import UIKit

static let BChangedNotification = "ViewControllerBChanged"

class ViewControllerB: UIViewController {

    //... truncated

    func valueChanged(sender: AnyObject) {
        let changedValue = ...
        NSNotificationCenter.defaultCenter().postNotificationName(
            BChangedNotification, object: changedValue)
    }

    //... truncated
}

Followed up with A looking something like this – where ValueType is simply the type of the value you mentioned:

import UIKit

class ViewControllerA: UITableViewController {

    //... truncated

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        //...truncated

        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: "onBChangedNotification:",
            name: BChangedNotification,
            object: nil)
    }

    //... truncated

    func onBChangedNotification(notification: NSNotification) {
        if let newValue = notification.object as? ValueType {

            //...truncated (do something with newValue)

            self.reloadData()
        }
    }
}

Lastly – don't forget to remove the observer in A's deinit method:

import UIKit

class ViewControllerA: UITableViewController {

    //... truncated 

    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    //... truncated
}
dangnabit
  • 654
  • 3
  • 9