DAY #5

What is the protocol-delegate communication pattern?

The Protocol-delegate pattern is a method of subscribing methods to an event.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
protocol ButtonPressedDelegate: AnyObject {
    func methodToBeImplemented()
}

class ReceivingClass: UIViewController, ButtonPressedDelegate {
    
    func methodToBeImplemented() { //Conform to protocol
        print(Button pressed)
    }

}

class SendingClass: UIViewController {
    weak var delegate: ButtonPressedDelegate? //Create field for reference. Use “weak var” to avoid retain cycle.
    
    @IBAction func send(_ sender: Any) {
        delegate.methodToBeImplemented() //Call method
    }
}

let receivingC = ReceivingClass()
let sendingC = SendingClass()
sendingC.delegate = receivingC.self //Pass the reference. Normally you would not do it like this, but this is the concept.

//Better places to assign a reference:
//-From inside cellForRowAt()
//-In a segue
//-As you instantiate sending class from receiving class

//Common errors:
//-Protocols are one-to-one. If you are trying to subscribe multiple receivers, you will need to implement a multicast delegate. Dm for code snippet.
//-Forgetting to assign self to delegate field in sending class.
//-Issues with “weak self”, make sure to conform the protocol to AnyObject

//For more code ideas, and a explanation an why we use “weak var”: https://medium.com/macoclock/delegate-retain-cycle-in-swift-4d9c813d0544

Originally published 04/07/2021 @ https://pittcsc.org/ Discord

Published here on 09/08/2022. Blog published date reflects the original date of publication.