icekomo
icekomo

Reputation: 9466

Delegate protocol not working, returns nil

I'm trying to use a protocol / delegate in swift, and while I'm not getting any errors it seems that my delegate is not being created. It is returning nil on me, and I'm not sure why.

Here is my code

Class 1

import UIKit

protocol GameViewSliding{
    func slideGameView()
}

class GameDetailsViewController: UIViewController {
var delegate:GameViewSliding?

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 showOptions(sender: AnyObject) {

    println("button pressed")
    println(delegate)
    delegate?.slideGameView()
}

}

Class 2 that conforms to the protocol

import UIKit

var currentHoleNumber:Int = 0
var parThree = false;
var parFive = false;

class GameViewController: UIViewController,  GameViewSliding{


var gameDetailsVC:GameDetailsViewController = GameDetailsViewController()
override func viewDidLoad() {
    super.viewDidLoad()

    println("inside the game class")
    gameDetailsVC.delegate = self
}

func slideGameView(){
    println("this is from the root controller")
}

}

Upvotes: 0

Views: 930

Answers (1)

Tim
Tim

Reputation: 2922

The problem is likely in the code you are not showing here. In prepareForSegue you usually want to set the delegate on the destination view controller.

Essentially you are setting it on an instance of the class that you are creating, but that isn't the instance that is actually shown. So the instance that is shown has no delegate.

Remove your local var of the second controller, and the setting of the delegate in the view did load and simply set it on the destination in prepare for segue and I bet it will work perfectly.

Upvotes: 2

Related Questions