Imma
Imma

Reputation: 73

Swift Delegate without prepareForSegue

I'm new to swift and ios development. I have two classes and want them to connect. I'm not using the prepareForSegue. This is what I have, something must be wrong somewhere.

protocol TimeDelegate{
 func timerDidFinish()
}


class Timer: UIViewController {

// this is where we declare our protocol
var delegate:TimeDelegate?

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func timeFired(sender: UIButton){

    delegate?.timerDidFinish()

}

}


import UIKit


class ViewController: UIViewController, TimeDelegate {

var timer:Timer = Timer()

override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func timerDidFinish(){

    println("Delegate is working")
}

}

For some reason, timerDidFinish is not firing.

Upvotes: 4

Views: 2622

Answers (1)

Raja Vikram
Raja Vikram

Reputation: 1980

From your explanation i gather that the two UIViewControllers are not linked in any way.

When you click the button to fire the @IBAction func timeFired(sender: UIButton){..} function, you will be in Timer UIViewController.

Then when are you instantiating ViewController ? Without instantiating it the delegate will never be set.

If you just want to call the timerDidFinish() func and want nothing else to do with ViewController then do this:

class Timer: UIViewController {

var delegate:TimeDelegate?

override func viewDidLoad() {
super.viewDidLoad()
var vc = ViewController()
self.delegate = vc

}

Then your function will be called.

Upvotes: 7

Related Questions