Upgrade to Pro — share decks privately, control downloads, hide ads and more …

MVVMって何? というか…MV○丸ごと、何?

 MVVMって何? というか…MV○丸ごと、何?

shibuya.swift #4 (http://shibuya-swift.connpass.com/event/31031/)
で発表したスライドです。

もっと詳しいMVVMの話はこちら:
健康的なMVVM 書いてますか? ~MVVMアンチパターン集~
(https://speakerdeck.com/takasek/jian-kang-de-namvvm-shu-itemasuka-mvvmantipatanji)

takasek

June 08, 2016
Tweet

More Decks by takasek

Other Decks in Programming

Transcript

  1. .PEFM $POUSPMMFS 7JFX ͪͳΈʹ.7$.PEFM XFCΞϓϦ ϦΫΤετ DMJFOU TFSWFS 1998೥ɺJSP(JavaServer Page)ͷ


    ࢓༷υϥϑτͰఏএ͞ΕͨΒ͍͠ MVCΛWebαʔϏεʹద༻ ObserverύλʔϯΛ
 ࢖Θͳ͍ (࢖͑ͳ͍)
  2. .PEFM J04Ͱ͋Γ͕ͪͳ.7$ ೖྗ 7JFX $POUSPMMFS 7JFX 7JFX EFMFHBUF UPVDI &WFOU

    4FFBMTP
 ͜Ε͕࠷ڧͷ.7$ J04 IUUQRJJUBDPNLPJUBSPJUFNTCBGEGB
  3. 7JFX .PEFM 1SFTFOUFS ೖྗ Φϒβʔόಉظ .71 ؂ࢹίϯτϩʔϥ CͰ͸ͳ͘
 Vͷ੹຿ ໾ׂ


    ɾೖྗΛModelʹ౉͢
 ɾPresentation Logic ͜͜͸ݹయతMVCͱಉ͡
 ςετͮ͠Β͍໰୊͸͋Δ

  4. .PEFM 7JFX.PEFM 7JFX %BUB #JOEJOH $PNNBOET .77. ೖྗ ɹσʔλόΠϯσΟϯάͷ࣮ݱͷͨΊʹ͸ɺJ04ͷ৔߹ ɹɹ'31ϥΠϒϥϦ

    3Y4XJGU 3FBDUJWF$PDPB ΍ ɹɹσʔλόΠϯσΟϯάϥΠϒϥϦ 4XJGU#POE ͷ ɹɹαϙʔτ͕ඞཁ ɹ ˞'J/$Ͱ͸ݱࡏ4XJGU#POEΛར༻
  5. class MyViewModel { weak var view: MyView? func doSomething(fuga: Fuga)

    { guard let view = view else { return } if view.isHoge { view.doSomething(fuga) } } } class MyView { func awakeFromNib() { viewModel.view = self } } ୯ํ޲ͷґଘؔ܎ ❌ ϨΠϠͷґଘؔ܎͕͓͔͍͠ɻ
 7.͕7JFXΛ஌ͬͯ͠·͍ͬͯΔ
  6. class MyViewModel { let fuga = Observable<Fuga?>(nil) func didReceiveFuga(fuga: Fuga)

    { self.fuga.value = fuga } } class MyView { func awakeFromNib() { viewModel.fuga.ignoreNil().observe { [weak self] in self?.doSomething($0) } } } ୯ํ޲ͷґଘؔ܎
  7. ୯ํ޲ͷॲཧϑϩʔ 7JFX.PEFM΁ͷίϚϯυ͕
 ɹॲཧͷ׬ྃ࣌ʹ࣮ߦ͢ΔΫϩʔδϟΛड͚ͨΓ class MyView { func awakeFromNib() { viewModel.alertMessage.observe

    { [weak self] in self?.showAlert($0) // ↓Ͳ͕ͬͪຊے!? } } func didTapButton() { viewModel.doSomething(completion: { [weak self] alertMessage in self?.showAlert(alertMessage) // ↑Ͳ͕ͬͪຊے!? }) } } ˠॲཧͷྲྀΕ͕ΧΦεʹʂ BMFSU.FTTBHF 0CTFSWBCMF4USJOH͕ มߋ͞ΕͨΒൃಈ ͳΜ͔΍ͬͨ݁Ռ BMFSU.FTTBHFΛ ड͚औΔ ❌
  8. class MyView { var viewType: ViewType func setup(viewType: ViewType) {

    self.viewType = viewType switch viewType { case .Title: viewModel.title.observe { ... } case .Image: viewModel.image.observe { ... } case .Detail: viewModel.detail.observe { ... } } } } ϏδωεϩδοΫͱϓϨθϯςʔγϣϯͷ෼཭ 7JFXଆʹঢ়ଶ΍৚݅෼ذ͕͋Δ ❌
  9. ʮ7JFX͸7JFX.PEFMͷӨʯΛ పఈͤ͞Δ class MyView { func awakeFromNib() { viewModel.title.observe {

    ... } viewModel.image.observe { ... } viewModel.detail.observe { ... } } } 7JFX͸Կ΋൑அΛߦΘͣɺ 7JFX.PEFMͷঢ়ଶΛ ໧ʑͱ6*ʹ൓өͤ͞Δ 7JFX.PEFM͸ɺ 7JFXΛ࠶ߏ੒Ͱ͖Δ͚ͩͷ ঢ়ଶ৘ใΛอ࣋͢Δ ϏδωεϩδοΫͱϓϨθϯςʔγϣϯͷ෼཭