-1

I'm trying to use delegates between two controllers but it doesn't work as it should be

protocol saveDelegate: class {
    func saveSite()
}
class AuditSiteViewController: UIViewController {
    weak var delegate: saveDelegate?

   @IBAction func saveButton(sender: UIBarButtonItem) {
        print("Saved")
        delegate?.saveSite()
    }
}


class AuditDetailsViewController: UIViewController,  saveDelegate {
     var mainView: AuditSiteViewController?

     override func viewDidLoad() {
        super.viewDidLoad()

        mainView?.delegate = self

    }

    func saveSite() {
        print("delegated")
    }
}

it should print delegated but it only prints "saved"?

Abdoelrhman
  • 906
  • 8
  • 17
  • I'm trying to fire save function from another viewcontroller, shouldn't i use delegates? or what? – Abdoelrhman Jul 23 '16 at 17:20
  • I tried to create it as an instance but i still got nothing, i was just following online resources about it to make it work so that's what i got, how can i solve this? with code if possible? – Abdoelrhman Jul 23 '16 at 17:30
  • You have a debugger. A wonderful debugger. Debug! – matt Jul 23 '16 at 18:12

3 Answers3

0

You can use delegate, but have you debug and check that mainView is the correct instance?

My suggestion in this case would be to use NSNotification instead. You can add a observer in your viewDidLoad and post a notification on the saveButton()

class AuditDetailsViewController: UIViewController {

  override func viewDidLoad() {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AuditDetailsViewController.saveSite), name: "SaveSite", object: nil)
  }
}

class AuditSiteViewController: UIViewController {

  @IBAction func saveButton(sender: UIBarButtonItem) {
    NSNotificationCenter.defaultCenter().postNotificationName("SaveSite", object: nil)
  }
}
Zac Kwan
  • 5,587
  • 4
  • 20
  • 27
0

In my opinion there are only two reasons possible:

First: In the moment of calling mainView?.delegate = self mainView is nil. Then the delegate isn't assigned. Set a breakpoint there and you will see it.

Second: In the moment of calling delegate?.saveSite() the delegate is nil. That may be because your instance of AuditDetailsViewController was deinit by you or system. System removes the instance if noone holds a strong reference to it anymore. Implement the deinit method and set a breakpoint in it to see when it happens.

ObjectAlchemist
  • 1,109
  • 1
  • 9
  • 18
0

Looks like the mainView is nil when you set the delegate. Try to set the reference when you instantiate the detail view controller.

Anyway, maybe what you want is to delegate the saving action from the detailViewController to the AuditSiteViewController and handle in this last VC the savings.

rockdaswift
  • 9,613
  • 5
  • 40
  • 46