Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active August 11, 2016 02:33
Show Gist options
  • Save KentarouKanno/13e45bfec2eed08f8a7f to your computer and use it in GitHub Desktop.
Save KentarouKanno/13e45bfec2eed08f8a7f to your computer and use it in GitHub Desktop.
Delegate

Delegate

image

上記図をコードにしたもの

// プロトコルAを定義(プロトコルAに準拠したものは、必ずmethodAを実装しなければいけない)
protocol ProtocolA: class {
    func methodA()
}

// プロトコルAに準拠したクラスAを定義
class ClassA: ProtocolA {

    // クラスBを生成
    var classB = ClassB()

    init () {
        // クラスBのdelegate変数に自分自身を設定
        // クラスAはプロトコルAに準拠しているので設定できる
        classB.delegate = self
    }

    // プロトコルAに準拠したため実装が必須のmethodA()
    func methodA() {
        // Action
    }
}

// クラスBを定義
class ClassB {

    // クラスAのインスタンスを格納するためのdelegate変数
    // 型はプロトコルA型
    weak var delegate: ProtocolA!

    func something() {
        // クラスAのインスタンスに対してmethodA()を呼び出す
        delegate?.methodA()
    }
}

★ required, optional

// @objc 修飾子を付ける

 @objc
protocol SampleDelegate: class {
    
    // required Method
    func requiredMethod()
    
    // optional Method
    optional func optionalMathod()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment