Skip to content

Latest commit

 

History

History

section16-delegate

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Delegate 1 ~ 2

1) What is Delegation?

Answer:

  • Delegation is one of the design pattern which is used to establish the communication between one to one objects.
protocol ADelegate {
    func eventOccured()
}

class A {

    var delegate: ADelegate?

    func makeEvent() {
        delegate?.eventOccured()
    }

}

class B: ADelegate {


    let a: A

    init(a: A) {
        self.a = a
        a.delegate = self
    }

    func eventOccured() {
        print("class A made an event")
    }

}

let a: A = A()
let b: B = B(a: a)
a.makeEvent() // class A made an event

2) Can delegate be a weak and why delegate must be weak?

Answer:

  • Delegate variable must be week because its parent reference object can be removed from the memory at any point of time.
protocol ADelegate: AnyObject {
    func eventOccured()
}

class A {

    // Declared with weak
    weak var delegate: ADelegate?

    func makeEvent() {
        delegate?.eventOccured()
    }

}

class B: ADelegate {

    let a: A

    init(a: A) {
        self.a = a
        a.delegate = self
    }

    func eventOccured() {
        print("class A made an event")
    }

}

Table Of Contents

Section 1, Data Type

Section 2, Operator

Section 3, Conditional Statement

Section 4, Enum

Section 5, functions

Section 6, struct

Section 7, initializers

Section 8, closures

Section 9, OOP

Section 10, static type vs dynamic type

Section 11, optional

Section 12, generic

Section 13, subscript

Section 14, access specifier

Section 15, higher order function

Section 16, delegate

Section 17, extension

Section 18, Memory Management

Section 19, protocols

Section 20, collections

Section 21, KVO and KVC

Section 22, Exception Handling

Section 23, Framework

Section 24, Objective-C