Last active
November 16, 2017 09:23
-
-
Save hmhmsh/01e85ef7ae3e1d1e807e6d2d66f9d080 to your computer and use it in GitHub Desktop.
デザインパターン入門「Model-View-Controller」 ref: https://qiita.com/hmhmsh/items/271a6cb309761bd965d3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ユーザーからの入力を受け取る | |
modelへ入力を伝える |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
データの保持 | |
データの管理 | |
ビジネスロジック |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// データの変更を通知するためにdelegateを実装 | |
protocol MVCModelDelegate: class { // ← class制約 | |
func didChange() | |
} | |
class MVCModel { | |
public var count = 0; | |
weak var delegate: MVCModelDelegate? = nil // ← 弱参照へ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
modelの情報を表示する |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment