1

got 2 ViewControllers 1st is ViewController 2nd TableViewCotnroller

    class ViewController: UIViewController, CLLocationManagerDelegate, TabVCDelegate {

        func reciveData(_ numberOfRows: Int) {
            print(numberOfRows)
        }
...
    }

TableViewController:

protocol TabVCDelegate {
    func reciveData(_ numberOfRows: Int)
}

class TabVC: UITableViewController {

    var delegate: TabVCDelegate?

    @IBAction func passDataBack(_ sender: UIButton) {
        delegate?.reciveData(5)
        self.dismiss(animated: true, completion: nil)
        print(delegate ?? "show me if its nil")
    }

my delegate?.reciveData(5) is for some reason nil can't figure it out it did worked when i had 2 normal ViewController am i missing something about TableViewControllers? or maybe its something else? any help would be appreciated.

LBandach
  • 92
  • 9

2 Answers2

1

First of:
Make that delegate property weak to avoid strong reference cycle

weak var delegate: TabVCDelegate?

To achieve that your protocol should conform to class

protocol TabVCDelegate: class {
    func reciveData(_ numberOfRows: Int)
}

Next:
You must set that delegate somewhere. If you have reference to TabVC instance in your ViewController class then it would look like this: tabVC.delegate = self

HERE is detailed description about "how to create delegates in Swift"

gorzki
  • 433
  • 3
  • 10
  • making it weak resulted in : 'weak' must not be applied to non-class-bound 'TabVCDelegate'; consider adding a protocol conformance that has a class bound" and i do not understand 2nd part i can't set anything like TabVC.delegate as i get expected declaration i guess it would need to be let/var but thats probably not what u mean thanks :) i'll try figure it out just a moment – LBandach Jul 25 '18 at 11:03
  • @LBandach I updated my answer. There is link to detailed description about how to create delegates. Also I don't know where you are creating instance of TabVC (let/var) so I'm not able to provide more precise code. – gorzki Jul 25 '18 at 11:22
0

thanks

actually i did found what was missing, in segue i forgot to set destinationVC.delegate as self when setting segue :

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "goToTableView"{
        let destinationVC = segue.destination as! TabVC

        destinationVC.delegate = self // <-- this line was missing 

        destinationVC.dataPassedThroughSegue = locationLabel.text
    }
}
LBandach
  • 92
  • 9
  • Glad you make it ;) That's what i meant in "next" step. Did you also marked delegate as `weak`? Thats very important. Otherwise you may expect memory leaks. – gorzki Jul 25 '18 at 12:00
  • em ye i realised :) for 1st i tried jut 2 declare delegate = self out of any function and thats where Xcode wanted this to be let/var em no but ill figure it out :) just now making lil break :P – LBandach Jul 25 '18 at 12:02