LoginSignup
7
7

More than 5 years have passed since last update.

デリゲートパターンの流れ図を描いてみた

Last updated at Posted at 2016-11-04

アクティビティ図0.png

コミュニケーション図0.png

いくつかのページを参照してデリゲートパターンを初めて実装したのですが、ページによって説明が異なっていて、プログラムが動くまで時間がかかりました。

これから実装する方の参考になればありがたいです。また、初めての実装なので、おかしい点があればご指摘いただけると幸いです。

以下のコードの括弧数字の部分が最初のアクティビティ図の数字と対応しています。

GraphViewController
import UIKit

// (1)
protocol GraphViewDelegate: class {  // ※
    // (2)
    func onModelUpdated(newValue: Float) -> Void
}

class GraphViewController: UIViewController {
    ...
    weak var delegate: GraphViewDelegate?  // (3)
    ...
    // セグエを使ってインスタンスを取得する
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "Plot" {
            //(4)
            let plotViewController = segue.destinationViewController as! PlotViewController
            // (5)
            self.delegate = plotViewController
        }
    }

    // モデルが変化するたびに走る
    override func observeValueForKeyPath(...
        let newValue = ...
        delegate!.onModelUpdated(newValue)  // (6)(7)
    }
}

※delegateをweakで宣言する際にprotocolにclassを継承する理由 - Qiita http://qiita.com/yimajo/items/892bd2fe1ccb808ffe49

PlotViewController
import UIKit

// (8)
class PlotViewController: UIViewController, GraphViewDelegate {
    ...
    func onModelUpdated(newValue: Float) {  // (9)
        ...
    }
}

ちなみに細かいことですがGraphViewDelegateの代わりにGraphViewControllerDelegateにしたらエラーになりました。謎…

GraphViewController
self.delegate = plotViewController

Cannot assign value of type 'PlotViewController' to type 'GraphViewControllerDelegate?'

よろしくお願いします。


ブログやっています:http://weed.nagoya

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7