Skip to content

Instantly share code, notes, and snippets.

@hmhmsh
Last active November 16, 2017 09:23
Show Gist options
  • Save hmhmsh/01e85ef7ae3e1d1e807e6d2d66f9d080 to your computer and use it in GitHub Desktop.
Save hmhmsh/01e85ef7ae3e1d1e807e6d2d66f9d080 to your computer and use it in GitHub Desktop.
デザインパターン入門「Model-View-Controller」 ref: https://qiita.com/hmhmsh/items/271a6cb309761bd965d3
ユーザーからの入力を受け取る
modelへ入力を伝える
データの保持
データの管理
ビジネスロジック
// データの変更を通知するためにdelegateを実装
protocol MVCModelDelegate: class { // ← class制約
func didChange()
}
class MVCModel {
public var count = 0;
weak var delegate: MVCModelDelegate? = nil // ← 弱参照へ
import Foundation
import UIKit
class MVCSubViewController: UIViewController {
var mvcModel: MVCModel? = nil
@IBOutlet weak var countLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// ⑤初期値を表示
if let count = mvcModel?.count {
countLabel.text = String(count)
}
}
}
extension MVCViewController {
// ②ユーザーからの入力イベント
@IBAction func display(_ sender: Any) {
// SubViewController画面に遷移
performSegue(withIdentifier: "presentMVCSubViewController", sender: self)
}
// ③画面遷移の際呼ばれる
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// ④遷移先のViewControllerにModelクラスを渡す
if let destination = segue.destination as? MVCSubViewController {
destination.mvcModel = mvcModel
}
}
}
modelの情報を表示する
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment