티스토리 뷰
MVC
이제까지 해 왔던 방법으로 View Controller를 구성해보자.
(우선 UI는 단순한 TableView에 음악 제목을 띄우기만 할 것이다.)
ViewController
class ViewController: UIViewController {
private var musicData: [Music]?
private let networkManager = NetworkManager.shared
private let tableView: UITableView = {
let table = UITableView()
table.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
return table
}()
override func viewDidLoad() {
super.viewDidLoad()
setTableView()
fetchData()
}
private func setTableView() {
view.addSubview(tableView)
tableView.frame = view.bounds
tableView.dataSource = self
}
private func fetchData() {
networkManager.requestData(term: "jazz") { result in
switch result {
case .success(let data):
self.musicData = data
DispatchQueue.main.async {
self.tableView.reloadData()
}
case .failure(let error):
print(error.localizedDescription)
}
}
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
musicData?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = musicData?[indexPath.row].musicTitle
return cell
}
}
View Controller의 역할을 보자.
뷰를 생성하고, NetworkManager의 인스턴스를 이용해서 직접 request 하고, 받아온 정보를 tableView에 업데이트 시켜주고 있다.
1. 뷰를 생성한다. (LifeCycle에 따라 관리)
2. NetworkManager에게 데이터를 요청한다.
(검색 기능이 있다면, 사용자의 입력 값을 감지하여 데이터를 요청하는 코드가 있을 것이다.)
3. Network 결과를 기반으로 TableView를 업데이트 시킨다.
'iOS > 아키텍처 패턴' 카테고리의 다른 글
UIKit에서 MVVM 알아보기 (MVC -> MVVM) - 3 (0) | 2023.05.24 |
---|---|
UIKit에서 MVVM 알아보기 (MVC -> MVVM) - 1 (0) | 2023.05.24 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 레플릿
- python
- SwiftUI
- CodeUp
- do while
- 깃
- 코드업
- Code up
- level1
- baekjoon
- 시간초과
- ord
- for문
- 기초 100제
- 정답
- 이것이 코딩테스트다
- 리플릿
- 백준
- COMMIT
- 반복문
- 설명
- 깃허브
- 파이썬
- 16진수 입력
- replit
- Swift
- 코드 업
- 프로그래머스
- 부르트포스
- CHR
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
글 보관함