YunDaeHyeon
← Lab

Swift의 Mode-View-Controller

스터디2025.06.05
  • Swift
  • MVC

Model-View-Controller

Model-View-Controller

Radu Dan - Doing magic things in Swift

Model-View-Controller

Model-View-Controller

Radu Dan - Doing magic things in Swift

Model-View-Controller (MVC) in iOS – A Modern Approach | Kodeco

Model-View-Controller (MVC) in iOS – A Modern Approach | Kodeco

medium.com/better-programming/battle-of-the-ios-architecture-patterns-model-view-controller-mvc-442241b447f6

MVC란 무엇인가?

Swift에서의 MVC는 앱의 구성 요소를 Mode, View, Controller로 구분하여 소프트웨어를 구조화하는 디자인 패턴을 말합니다.

각각의 구성 요소는 명확한 역할과 책임을 부여해 유지보수성과 확장성을 높이기 위해 활용됩니다.

이미지 출처 : https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/MVC.html

실제 Apple 문서에는 다음과 같이 MVC를 정의하고 있습니다.

_The Model-View-Controller (MVC) design pattern assigns objects in an application one of three roles: model, view, or controller. The pattern defines not only the roles objects play in the application, it defines the way objects communicate with each other. Each of the three types of objects is separated from the others by abstract boundaries and communicates with objects of the other types across those boundaries. The collection of objects of a certain MVC type in an application is sometimes referred to as a layer—for example, model layer.

”모델-뷰-컨트롤러(MVC) 디자인 패턴은 애플리케이션의 객체에 모델, 뷰, 컨트롤러의 세 가지 역할 중 하나를 할당합니다. 이 패턴은 애플리케이션에서 객체가 수행하는 역할뿐만 아니라 객체 간 통신 방식도 정의합니다. 세 가지 유형의 객체는 각각 추상적인 경계로 분리되어 있으며, 이러한 경계를 통해 다른 유형의 객체와 통신합니다. 애플리케이션에서 특정 MVC 유형의 객체 모음을 레이어 ( 예: 모델 레이어)라고 부르기도 합니다.”_


Model, View, Controller의 역할과 책임

MVC에서의 모델과 뷰, 컨트롤러는 명확한 역할과 책임을 구분짓고 부여해야합니다.

어떠한 기준으로 각각의 구성 요소에 역할과 책임을 부여할 것인지.. 저같은 경우는 상대적으로 어렵게 느껴졌습니다. 공식 문서를 기반으로 각각의 구성 요소의 역할과 책임을 부여하는 기준을 아래와 같이 정리해보겠습니다.

MVC의 흐름을 아래와 같이 그려보았습니다.

📌 Model

_공식 문서에서 정의하는 Model의 설명_

Model objects encapsulate the data specific to an application and define the logic and computation that manipulate and process that data. For example, a model object might represent a character in a game or a contact in an address book. A model object can have to-one and to-many relationships with other model objects, and so sometimes the model layer of an application effectively is one or more object graphs. Much of the data that is part of the persistent state of the application (whether that persistent state is stored in files or databases) should reside in the model objects after the data is loaded into the application. Because model objects represent knowledge and expertise related to a specific problem domain, they can be reused in similar problem domains. Ideally, a model object should have no explicit connection to the view objects that present its data and allow users to edit that data—it should not be concerned with user-interface and presentation issues.

  • 공식문서에서의 Model은 앱의 고유한 데이터를 캡슐화하고 데이터를 조작하고, 처리하는 로직을 정의한다고 말합니다.
  • 쉽게 설명해보자면 Model은 게임의 캐릭터나 주소록의 연락처를 정의하는 역할을 수행함을 말합니다.
  • ⭐ 이상적으로 Model은 데이터 뷰 객체와 명시적으로 연결되어 있지 않아야 합니다.
- 역할 : Model은 앱의 데이터와 비즈니스 로직을 담당하는 계층입니다. - 책임 - Model은 데이터의 생성, 저장, 가공 등의 책임을 집니다. - 비즈니스 규칙(유효성 검사, 계산 등)을 수행합니다. - 데이터 변경 발생 시 Controller에게 알려야합니다. - ⭐ MVC구조에서 모델은 View(UI)와 직접적인 상호작용을 절대 하지 않습니다. - 예시
struct Task {
    let title: String
    let isCompleted: Bool
}
  • 흐름
  1. View에서 사용자가 데이터를 입력하거나 사용자 이벤트(동작)가 발생하면 해당 동작은 Controller에게 전달됩니다.
  2. 그 후 Controller는 Model을 생성하거나 업데이트합니다.
  3. Model이 수정되면, Controller에게 알람을 보냅니다.
  4. Controller는 해당 변경 사항을 반영하기 위해 View를 업데이트합니다.

📌 View

_공식 문서에서 정의하는 View의 설명_

A view object is an object in an application that users can see. A view object knows how to draw itself and can respond to user actions. A major purpose of view objects is to display data from the application’s model objects and to enable the editing of that data. Despite this, view objects are typically decoupled from model objects in an MVC application.

Because you typically reuse and reconfigure them, view objects provide consistency between applications. Both the UIKit and AppKit frameworks provide collections of view classes, and Interface Builder offers dozens of view objects in its Library.

  • View는 앱에서 사용자가 직접적으로 볼 수 있는 객체를 의미합니다.
  • View는 자기 자신을 그리는 방법을 알고 있습니다.
  • View의 주요 목적은 Model의 데이터를 표시하고, 편집할 수 있게 하는 것입니다.
- 역할 : View는 Model의 시각적 표현 및 사용자와의 상호작용을 담당합니다. - 책임 - View는 사용자에게 정보를 보여줍니다. - 사용자로부터 입력(터치, 제스처 등)을 받습니다. - ⭐ Model의 데이터를 View를 활용하여 표시하지만, 직접적으로 Model을 조회하거나 수정하지 않아야 합니다. - UIKit에서 UIView, UILabael, UIButton, UITableView 등 모든 UI 객체를 의미합니다. - 예시
class TaskTableViewCell: UITableViewCell {
    func configure(with task: Task) {
        textLabel?.text = task.title
    }
}
  • 흐름
  1. View는 Controller를 통해 Model의 변경 사항을 파악합니다.
  2. 사용자의 입력이 발생되면 View는 이벤트를 Controller에 알립니다.
  3. Controller는 변경 사항을 Model에게 전달합니다.

📌 Controller

_공식 문서에서 정의하는 Controller의 설명_

A controller object acts as an intermediary between one or more of an application’s view objects and one or more of its model objects. Controller objects are thus a conduit through which view objects learn about changes in model objects and vice versa. Controller objects can also perform setup and coordinating tasks for an application and manage the life cycles of other objects.

  • ⭐ Controller는 Model과 View 사이의 중개자 역할을 수행합니다.
  • Controller는 View나 Model의 변경 사항을 파악합니다.
  • Controller는 iOS 애플리케이션의 설정 및 다양한 작업을 수행합니다.
  • Controller는 다른 객체의 수명 주기를 관리할 수 있습니다.
- 역할 : Controller는 Model과 View 사이의 중개자 역할을 담당하며 `비즈니스 로직과 UI를 연결하는 핵심 역할을 수행합니다.` - 책임 - View에서 발생한 사용자 이벤트(버튼 클릭, 입력, 제스처 등)에 대응해야합니다. - Model의 상태를 변경하거나 데이터를 요청해야합니다. - Mode이 변경되면 이를 View에 반영하여 UI를 갱신해야합니다. - ⭐ View와 Model은 절대 직접적으로 접근하지 않아야 하며, Controller를 통해 상호작용 해야합니다. - 흐름 1. Controller는 View에서 수행된 사용자의 동작을 해석한 뒤 변경된 데이터를 Model에 전달합니다. 2. Model이 변경되면 Controller는 변경 사항을 View에 전달하여 사용자에게 표시합니다.

쉽게 정리해보면 아래와 같이 MVC 계층간 흐름을 정리할 수 있습니다.

  • 사용자 동작 → View → Controller → Model (데이터 변경)
  • Model의 데이터 변경 발생 → Controller → View (UI 갱신)