0

H!

I using a tutorial learing swift and now I want to know if this is possible.

Or how to do this a better way.

AController.swift

protocol AControllerProtocol {
    func updateGui()
}

class AController {
    func doSomething(){
    // here I get incomming data and other stuff
    // then the gui in multiple views needs an update
    self.delegate.updateGui()
    }

    var delegate: AControllerProtocol
    init(delegate: AControllerProtocol) {
    self.delegate = delegate
    }
}

BViewController.swift

class BViewController: AController {
    @IBOutlet var tableView: UITableView!
    var acontroller : AController?

    override func viewDidLoad() {
    super.viewDidLoad()
    acontroller = AController(delegate: self)
    }

    func updateGui() {
    // dispatch_async(dispatch_get_main_queue(), {
    self.tableView!.reloadData()
    // works, it runs this method and this tables is inside this BViewController 
    // })
    }
}

CViewController.swift

class CViewController: AController {
    lazy var acontroller : AController = AController(delegate: self)

    @IBOutlet weak var tracksTableView: UITableView!

    func updateGui() {
        // dispatch_async(dispatch_get_main_queue(), {
        self.tracksTableView!.reloadData()
        // din't run, this table is only in this CViewController
        // it only did run BViewController updateGui()
    // })
    }
}

As you can see I have two views:

BViewController.swift

  • tableView

CViewController.swift

  • tracksTableView

AController get some data and then fires the delegate. I thought it will run the delegate in both views, so it can work in multiple classes, but it don't. It only runs inside the BViewController.swift

Then I thought, maybe this is not the correct way to do this, (pushing updates to other classes).

A simple other solution would be something like this ?

BViewController.swift

class BViewController: AController {
    @IBOutlet var tableView: UITableView!
    var acontroller : AController?

    override func viewDidLoad() {
        super.viewDidLoad()
        acontroller = AController(delegate: self)
    }

    func updateGui() {
    // dispatch_async(dispatch_get_main_queue(), {
    self.tableView!.reloadData()

    // get to know how to do this here
    CViewController.tracksTableView!.reloadData()
    // })
    }
}

CViewController.swift

class CViewController {
    @IBOutlet weak var tracksTableView: UITableView!
}

Greetings, Martijn

1 Answers1

2

Have a look at NotificationCenter.

A controller could fire a notification when data arrives and dispatch it to the NotificationCenter.

B and C view controller could listen for that notification and add an observer with NotificationCenter. Their handlers would be triggered when the notification is posted.

Charlton Provatas
  • 2,184
  • 25
  • 18
bandejapaisa
  • 26,576
  • 13
  • 94
  • 112