Last active
January 20, 2018 13:31
-
-
Save hmhmsh/d660a83e01d9d2c6e7a7d9a2ea4a098c to your computer and use it in GitHub Desktop.
MVVMを2パターン考えてみる(追記:MVPでしたすみません) ref: https://qiita.com/hmhmsh/items/263f1f531c220eb781ee
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
struct Entity { | |
let name: String | |
let age: Int | |
} | |
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
struct Model { | |
let name: String | |
let age: Int | |
} |
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 MVVMViewController: UITableViewDelegate, UITableViewDataSource { | |
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return viewModel.getModelCount() | |
} | |
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "MVVMCell", for: indexPath) | |
cell.textLabel?.text = viewModel.getName(index: indexPath.row) | |
return cell | |
} | |
} |
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
protocol RepositoryToViewModel: class { | |
func onGetModels(models: [Model]) | |
} | |
class Repository { | |
weak var viewModel: RepositoryToViewModel? | |
func getModels() { | |
// 通信などで取得する | |
// 今回は仮で作成 | |
var models = [Model]() | |
models.append(Model(name: "tarou", age: 25)) | |
models.append(Model(name: "zirou", age: 20)) | |
models.append(Model(name: "saburou", age: 18)) | |
viewModel?.onGetModels(models: models) | |
} | |
} |
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
class ViewModel { | |
private var models: [Model] = [] { | |
didSet { | |
view?.onChangeModels() | |
} | |
} | |
/* 省略 */ | |
func getModelCount() -> Int { | |
return models.count | |
} | |
func getName(index: Int) -> String { | |
return models[index].name | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment