0

I am new in Swift. I'm trying to understand how the delegate pattern works. Below is some code that I have tried to implement. The goal is to execute one method (printing()) from another class. I cannot achieve the expected behaviour for some reasons.

The first class:

protocol  ViewControllerDelegate: class {
    func printing()
}

class ViewController: UIViewController {
    weak var delegate: ViewControllerDelegate?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func button(_ sender: Any) {
        delegate?.printing()
    } 
}

The second class:

class Class: UIViewController,ViewControllerDelegate {
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let vc = ViewController()
        vc.delegate = self
    }

    func printing () {
        print("PRINT")
    }
}
AndreiT
  • 1
  • 1
  • How are you creating you presenting your VCs? From code or using a storyboard? – Dávid Pásztor Oct 12 '20 at 15:12
  • @DávidPásztor I use storyboard (segue). – AndreiT Oct 12 '20 at 15:17
  • 1
    Is `delegate?.printing()` even called? If yes, could you check the value of `delegate?`. I'm wondering if because `let vc = ViewController()` is a local variable, it might be released too soon. If that's the case, make `vc` a property of your `Class` instance. Else, it's because `button(_sender:)` isn't called, and that's another issue. Because when you do `ViewController()` you are creating a new instance, not the on you pushed/presented/see with your segue. – Larme Oct 12 '20 at 15:21
  • @DávidPásztor I used Class(UIViewController) because it is more clear for me in terms of implementing the delegate pattern. My original goal was to implement a method from another class that is UIView: class Class: UIView, ViewControllerDelegate { func printing () { print("PRINT") } } – AndreiT Oct 12 '20 at 15:23
  • @Larme I checked the value of delegate? . Delegate.ViewControllerDelegate? nil – AndreiT Oct 12 '20 at 15:30
  • It's "it is more clear for me in terms of implementing the delegate pattern", yes and no. It's simpler indeed, but in reality, as said, the ViewController that you are seing is not `vc`. You create a whole new instance. Just like when you do `let myVar1 = Something(); let myVar2 = Something()`, it doesn't mean that's the one you see on screen. – Larme Oct 12 '20 at 15:32
  • @Larme Thank you so much! ```override func prepare(for segue: UIStoryboardSegue, sender: Any?)``` works for this case. Could you please give me a hint about what should be done in case of ```class Class: UIView``` ? If I want to call a function from another class without presenting anything. Maybe I should use a singleton pattern. – AndreiT Oct 12 '20 at 16:08

0 Answers0