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에 μ—…λ°μ΄νŠΈ μ‹œμΌœμ£Όκ³  μžˆλ‹€.

λ˜ν•œ, 뷰에 λŒ€ν•œ μ½”λ“œλ„ κ°€μ§€κ³  μžˆλ‹€.

즉, μ§€κΈˆ View Controller의 역할은 λ·°λ₯Ό 그리고, 데이터λ₯Ό μš”μ²­ν•œ ν›„ 자기 μžμ‹ μ˜ ν…Œμ΄λΈ”μ„ λ³€κ²½ν•˜κ³  μžˆλŠ” λͺ¨μŠ΅μ„ λ³Ό 수 μžˆλ‹€.

λ§Œμ•½, μ‚¬μš©μžκ°€ μ•±μ—μ„œ 검색을 ν•˜κ³ , κ·Έ κ²°κ³Όλ₯Ό λ°›μ•„μ™€μ•Όν•œλ‹€λ©΄?

View controllerλŠ” μ‚¬μš©μžμ˜ μž…λ ₯을 κ°μ§€ν•˜κ³ , Network Managerμ—κ²Œ 검색어에 λŒ€ν•œ κ²°κ³Όλ₯Ό μš”μ²­ν•˜κ³ , NetworkManager의 κ²°κ³Όλ₯Ό 받아와 Table Viewλ₯Ό μ—…λ°μ΄νŠΈ ν•΄μ•Όν•œλ‹€

Last updated