Swift

MVC 패턴이란?

garlic 2020. 12. 22. 10:00

 

출처 : https://www.codeproject.com/Articles/879896/Programming-in-Java-using-the-MVC-Architecture

 

MVC 패턴은 Model - View - ViewController로 이루어진 형태의 desgin pattern이다. 현재 iOS에서 굉장히 많이 사용되고 있는 디자인 패턴이며, 애플에서 권장하는 디자인 패턴이기도 하다. 하지만 최근 MVVM 패턴의 선언형 프레임워크인 SwiftUI가 나오면서 필자는 사용해 본적 없는 MVVM 패턴과 MVC 패턴의 차이점을 명확히 알고자 정리하게 되었다.

 


들어가기 전 간단정리!

  1. Model은 앱에서 사용되는 데이터들을 관리 및 구성(?)하는 역할

  2. View는 데이터를 보여주는 역할이다.

  3. ViewController는 View와 Model의 사이에서 유저의 인터렉션을 처리해주어 액션에 따라 View와 Model간의 중재를 한다. Model을 업데이트 해주고 Model과 View를 연결해준다! (참고 UIViewController란? : garlic-onion.tistory.com/12)

*번역 실력이 부족하다는 점 알아주세요 ㅠㅜ

 


 

Model Objects Encapsulate Data and Basic Behaviors 

-> Data와 기본 행동들을 캡슐화하는 Model Object

 

Model objects represent special knowledge and expertise. They hold an application’s data and define the logic that manipulates that data. A well-designed MVC application has all its important data encapsulated in model objects. Any 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 once the data is loaded into the application. Because they represent knowledge and expertise related to a specific problem domain, they tend to be reusable.

 

-> Model 객체들은 특별한 지식과 전문 지식을 나타낸다. 이들은 앱의 데이터들을 가지고 있고, 이 데이터들을 조절할 수 있는 로직을 정의한다. 잘 디자인된 MVC 앱은 model object들에 모든 중요한 데이터들을 캡슐화하여 가지고 있다. 데이터들이 앱으로 들어왔을때, 앱에서 지속적으로 사용되는 어떤 데이터들(파일들이나 DB에 저장된 데이터)는 model 객체로 들어가져야 한다. 이 데이터들은 특정 부분들에서 재사용될 수 있기 때문이다.

 

 

 

Ideally, a model object has no explicit connection to the user interface used to present and edit it. For example, if you have a model object that represents a person (say you are writing an address book), you might want to store a birthdate. That’s a good thing to store in your Person model object. However, storing a date format string or other information on how that date is to be presented is probably better off somewhere else.

 

-> 이상적으로, model object는 보여지거나 수정하는 UI와 직접적으로 연결되지 않는 것이 좋다. 예를 들어, person 을 표현하는 model 객체가 있고, 당신은 birdthdate를 저장하기를 원한다고 가정하자. Person model 객체에 저장하는 것은 좋은 생각이다. 그러나 날짜 표시 형식과 같은 정보들은 person 객체 내부가 아닌 다른 곳에다가 저장하는 것이 더 나을 수도 있다.

 

 

 

In practice, this separation is not always the best thing, and there is some room for flexibility here, but in general a model object should not be concerned with interface and presentation issues. One example where a bit of an exception is reasonable is a drawing application that has model objects that represent the graphics displayed. It makes sense for the graphic objects to know how to draw themselves because the main reason for their existence is to define a visual thing. But even in this case, the graphic objects should not rely on living in a particular view or any view at all, and they should not be in charge of knowing when to draw themselves. They should be asked to draw themselves by the view object that wants to present them.

 

-> 실제로 이러한 구분이 항상 최선은 아니고 약간의 조절이 가능하지만, 일반적으로 model 객체는 interface와 보여지는 부분에 있어서 이슈가 있어서는 안된다. 약간의 합리적인 예외로는 graphic를 보여주는 model object를 가지고 있는 그리기 앱의 경우이다. graphic 객체들이 그들이 어떻게 그려져야 하는지를 아는 것은 타당하다. 핵심 이유로는 그들은 시각적이 것을 정의하기 때문이다. 그러나 이런 케이스에서, graphic 객체들은 그 어떤 뷰에도 의존하여서는 안되고, 언제 자신이 그려질지를 책임져서는 안된다. 그들은 그들을 표현하고자 하는 view 객체로 부터 언제 그려질지를 요청받아야 한다.

 

 


View Objects Present Information to the User

-> 유저에게 정보를 보여주는 View 객체

 

A view object knows how to display, and might allow users to edit, the data from the application’s model. The view should not be responsible for storing the data it is displaying. (This does not mean the view never actually stores data it’s displaying, of course. A view can cache data or do similar tricks for performance reasons). A view object can be in charge of displaying just one part of a model object, or a whole model object, or even many different model objects. Views come in many different varieties.

 

-> View 객체는 앱의 모델의 데이터를 표시하는 방법을 알고 있고, 사용자가 수정할 수 있도록 한다. view는 보여지는 data를 저장할 수 없다. (이 문장이 view는 실제 보여지는 data를 절대로 저장할 수 없다는 말은 아니다. 물론 view는 data를 cache 하거나 퍼모먼스 상의 이유들로 약간의 trick을 할 수는 있다.) View 객체는 model 객체의 한 부분을 그저 보여주거나 전체 모델 객체 또는 다양한 모델 객체를 표시할 수 있다. view들은 여러 부분에 관여할 수 있다.

 

 

 

 

View objects tend to be reusable and configurable, and they provide consistency between applications. In Cocoa, the AppKit framework defines a large number of view objects and provides many of them in the Interface Builder library. By reusing the AppKit’s view objects, such as NSButton objects, you guarantee that buttons in your application behave just like buttons in any other Cocoa application, assuring a high level of consistency in appearance and behavior across applications. 

 

-> View 객체들은 재사용 가능하고, 설정가능한 경우가 있다. 그리고 그들은 앱 내에서 계속 지속된다. Cocoa에서, AppKit 프레임워크는 다수의 뷰 객체들을 정의하고 Interface Builder library에서 그들을 제공한다. UIButton과 같은 AppKit의 뷰 객체들을 재사용함으로서, 앱 내에서 이 버튼이 다른 Cocoa 앱의 button처럼 동작하는 것을 보장할 수 있고, 앱에서 동작과 존재의 영속성을 보증할 수 있다.

 

 

 

A view should ensure it is displaying the model correctly. Consequently, it usually needs to know about changes to the model. Because model objects should not be tied to specific view objects, they need a generic way of indicating that they have changed. 

 

-> view는 model을 정확하게 보여주어야 한다. 따라서 뷰는 model의 변화를 알아야 한다. model 객체들은 특정 view 객체들에 묶여있지 않고, model 객체들은 모델의 변화를 감지할 수 있는 방법이 필요하기 때문이다.

 

 

 

 

 

Controller Objects Tie the Model to the View

-> Model을 View 객체 연결해주는 Controller 객체

 

A controller object acts as the intermediary between the application's view objects and its model objects. Controllers are often in charge of making sure the views have access to the model objects they need to display and act as the conduit through which views learn about changes to the model. Controller objects can also perform set-up and coordinating tasks for an application and manage the life cycles of other objects.

 

-> Controller 객체는 뷰 객체와 model 객체 사이에서 중재자 역할을 한다. Controller는 View가 보여져야할 model 객체에 접근하도록 하고, 뷰가 모델의 변경에 대해 알 도록 하는 통로 역할을 한다. Controller 객체는 앱을 위한 설정 및 조정 작업을 실행하고, 다른 객체들의 life cycles을 관리한다.

 

 

In a typical Cocoa MVC design, when users enter a value or indicate a choice through a view object, that value or choice is communicated to a controller object. The controller object might interpret the user input in some application-specific way and then either may tell a model object what to do with this input—for example, "add a new value" or "delete the current record"—or it may have the model object reflect a changed value in one of its properties. Based on this same user input, some controller objects might also tell a view object to change an aspect of its appearance or behavior, such as telling a button to disable itself. Conversely, when a model object changes—say, a new data source is accessed—the model object usually communicates that change to a controller object, which then requests one or more view objects to update themselves accordingly.

 

-> 전형적인 Cocoa MVC 디자인에선, 유저들이 view 객체를 통해 값을 입력하고 선택을 지시할 때, 그 값과 선택은 controller 객체로 전달한다. Controller 객체는 어떤 앱의 구체적인 방식으로 유저의 input을 해석할 수 있고, 그 다음 model 객체에 "새로운 값 추가"나 "현재 기록 삭제"와 같은 입력으로 무엇을 해주어야 하는지 알려주거나 모델 객체가 해당 property 중 하나에서 변경된 값을 반영하도록 할 수 있다. 이런 유저의 입력값에 기초하여, 몇몇 controller 객체들은 view 객체에게 button 자체를 사용하지 말도록 설정하는 등의 모양이나 동작 등을 변경하도록 지시할 수 있다. 반대로, 새로운 data source에 접근하여 model 객체가 변경되면, model 객체가 변경 내용을 controller 객체에게 전달한 다음 그에 다라 하나 이상의 view 객체들이 업데이트를 요청한다.

 

 

 

Controller objects can be either reusable or nonreusable, depending on their general type. Types of Cocoa Controller Objects describes the different types of controller objects in Cocoa.

 

-> Controller 객체들은 일반적인 type에 따라 재사용 될 수도, 안될 수도 있다. Types of Cocoa Controller Objects 를 참고하라.

 

 

 

참고

애플은 처음에 MVC 패턴을 권했지만 사용하다 보니 점점 ViewController에 들어가는 내용들이 점점 방대해져 가서 Massive View Controller라고 불릴 정도로 복잡해져 갔다. View Controller가 처리해야할 것들이 너무 방대해지고 복잡해지다보니 이러한 문제점들을 해결하기 위해서 다양한 디자인 패턴들을 사용하게 된 것이다. 왜 다른 디자인 패턴들이 나오게 되었는지 알아두면 좋을 것 같아 첨부했다.

 

 

 

 

 

 

참고 링크 :

developer.apple.com/library/archive/documentation/General/Conceptual/CocoaEncyclopedia/Model-View-Controller/Model-View-Controller.html

 

Model-View-Controller

Model-View-Controller The Model-View-Controller design pattern (MVC) is quite old. Variations of it have been around at least since the early days of Smalltalk. It is a high-level pattern in that it concerns itself with the global architecture of an applic

developer.apple.com