MVC 패턴

도윤·2021년 7월 28일
0

iOS

목록 보기
1/11

iOS의 가장 기본적인 design pattern인 MVC패턴에 대해 작성할 것입니다!


MVC 패턴

iOS에서 가장 기본이 되는 패턴인 MVC 패턴은 Model,View,Controller의 구조 아키텍쳐 입니다.

  • Model : 데이터와 로직을 다루는 부분으로 클래스나 구조체 등을 작성한다.
  • View : UI부분을 담당한다
  • Controller : model에 데이터를 요청하고 받은 데이터를 view로 보내고 view의 input 값을 받는 등 Model과 View의 중재자 역할을 한다.

controller는 Model과 View와 직접적인 통신이 가능하지만 Model과 View 사이에는 직접적인 통신이 불가능하여 Controller를 통하여 통신해야 한다.

하나의 controller 파일에서 여러 코드를 보게되면 가독성이 떨어지고 관리하기가 힘들어진다.

이렇게 함으로써 가독성이 증가하여 코드 관리가 쉬워지는 장점이 있습니다!

View ~ Controller

Contoller는 view에서 사용할 target을 지정해준다. 주로 우리가 선언하는 IBOutlet같은 경우이다.
View에서 UI에서 발생한 action을 Controller의 target에게 action을 전달하고 Controller가 작업을 수행하게 된다.

View는 View에서 보여주는 데이터들을 직접 관리할 수 없고 Controller를 통해서 보여주게 된다.

Model ~ Controller

Controller가 View의 action에서 발생한 요청을 처리하기 위해 Model에 저장된 데이터에 접근하여 수정하거나 가져와서 View를 업데이트한다.


코드 예시

해당하는 코드들은 https://www.udemy.com/user/4b4368a3-b5c8-4529-aa65-2056ec31f37e/ 의 Section9의 수업 내용입니다!

Model(M)

Question.swift

import Foundation

struct Question {
    let text : String
    let answer : [String]
    let correctAnswer : String
    init(q:String,a:[String],correctAnswer:String){
        text = q
        answer = a
        self.correctAnswer = correctAnswer
    }
}

Question.swift는 구조체로 Question의 text,answer,correctAnswer 프로퍼티를 선언하였다.

QuizBrain.swift

import Foundation

struct QuizBrain{
    let quiz = [
        Question(q: "Which is the largest organ in the human body?", a: ["Heart", "Skin", "Large Intestine"], correctAnswer: "Skin"),
        Question(q: "Five dollars is worth how many nickels?", a: ["25", "50", "100"], correctAnswer: "100"),
        Question(q: "What do the letters in the GMT time zone stand for?", a: ["Global Meridian Time", "Greenwich Mean Time", "General Median Time"], correctAnswer: "Greenwich Mean Time"),
        Question(q: "What is the French word for 'hat'?", a: ["Chapeau", "Écharpe", "Bonnet"], correctAnswer: "Chapeau"),
        Question(q: "In past times, what would a gentleman keep in his fob pocket?", a: ["Notebook", "Handkerchief", "Watch"], correctAnswer: "Watch"),
        Question(q: "How would one say goodbye in Spanish?", a: ["Au Revoir", "Adiós", "Salir"], correctAnswer: "Adiós"),
        Question(q: "Which of these colours is NOT featured in the logo for Google?", a: ["Green", "Orange", "Blue"], correctAnswer: "Orange"),
        Question(q: "What alcoholic drink is made from molasses?", a: ["Rum", "Whisky", "Gin"], correctAnswer: "Rum"),
        Question(q: "What type of animal was Harambe?", a: ["Panda", "Gorilla", "Crocodile"], correctAnswer: "Gorilla"),
        Question(q: "Where is Tasmania located?", a: ["Indonesia", "Australia", "Scotland"], correctAnswer: "Australia")
        
        
    ]
    
    var questionIndex = 0
    var score = 0
    
    mutating func checkAnswer(_ userAnswer:String) -> Bool{
        if userAnswer == quiz[questionIndex].correctAnswer {
            score += 1
            return true
        } else {
            return false
        }
    }
    
    func getQuestionText() -> String {
        return quiz[questionIndex].text
    }
    
    func getProgress() -> Float {
        return Float(questionIndex)/Float(quiz.count)
    }
    
    mutating func nextQuestion() {
        if questionIndex + 1 < quiz.count {
            questionIndex += 1
        } else {
            questionIndex = 0
            score = 0
        }
    }
    
    func getScore() -> Int {
        return score
    }
    
    func getAnswer() -> [String] {
        return quiz[questionIndex].answer
    }
}

QuizBrain은 구조체에 Quiz을 설정하였고, 이 Controller에서 퀴즈에 접근하는 모든 메서드를 선언하여 해당 프로퍼티들을 접근하여 값을 얻고 수정하도록 하였다.

Controller(C)

ViewContoller.swift

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var questionLabel: UILabel!
    @IBOutlet weak var progressBar: UIProgressView!
    
    @IBOutlet weak var choice2Button: UIButton!
    @IBOutlet weak var choice1Button: UIButton!
    @IBOutlet weak var choice3Button: UIButton!
    @IBOutlet weak var scoreLabel: UILabel!
    
    var quizBrain = QuizBrain()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        updateUI()
    }
    
    @IBAction func answerButton(_ sender: UIButton!) {
        
        let userAnswer = sender.currentTitle!
        sender.backgroundColor = quizBrain.checkAnswer(userAnswer) ? UIColor.green : UIColor.red
        quizBrain.nextQuestion()
        Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(updateUI), userInfo: nil, repeats: false)
    }
    
    @objc func updateUI(){
        
        let quizAnswer = quizBrain.getAnswer()
        questionLabel.text = quizBrain.getQuestionText()
        
        choice1Button.setTitle(quizAnswer[0], for: .normal)
        choice2Button.setTitle(quizAnswer[1], for: .normal)
        choice3Button.setTitle(quizAnswer[2], for: .normal)
        
        progressBar.progress = quizBrain.getProgress()
        scoreLabel.text = "Score : \(quizBrain.getScore())"
        
        choice1Button.backgroundColor = .clear
        choice2Button.backgroundColor = .clear
        choice3Button.backgroundColor = .clear
        
    }
    
}

Controller에서 Medel에 접근하여 해당하는 데이터들을 얻고 퀴즈 정답을 선택하는 버튼이 클릭되었을 때 설정한 구조체의 get메서드들을 이용하여 요청을 처리하는 코드입니다.

View(V)

!

Main.storyboard


수업 내용중 MVC 관한 내용이 있어서 복습할 겸 정리해보았습니다!

출처
https://www.udemy.com/user/4b4368a3-b5c8-4529-aa65-2056ec31f37e/
https://web.stanford.edu/class/cs75n/1_MVC.pdf

0개의 댓글