[Swift] MVP 패턴이 뭘까..?

GomMinjae·2021년 9월 13일
0

디자인패턴🌈

목록 보기
2/2
post-thumbnail

MVP 패턴은 Model, View,Presenter 로 이루어진 패턴입니다. MVP패턴은 Apple의 cocoa MVC와 비슷한 모습을 하고있습니다. MVP는 MVC패턴과는 다르게 Presenter라는 새로운 개념이 있습니다. Presenter은 ViewController life cycle에 영향을 받지 않습니다. Presenter는 Controller의 역할을 맡게 되고 데이터와 상태에 따라 View를 갱신하는 역할을 합니다. 정리하자면 Presenter는 Model로 부터 갱신된 데이터를 받아서 View를 업데이트하는 역할을 합니다.

Example

  • Model
struct Person {
  let name: String
  let age: Int
}
  • Presenter
protocol CustomView: class {
  func setCustomView(custom: String)
}

protocol CustomViewPresenter {
  init(view: CustomView, person: Person)
  func showView()
}

class CustomPresenter: CustomViewPresenter {
  weak var view: CustomView?
  var person: Person
  
  required init(view: customView, person: Person) {
    self.view = view
    self.person = person
  }
  func showView() {
    let message = "Hello \(self.person.name)"
    self.view?.setCustomView(custom: message)
  }
}
  • View
class ViewController: UIViewController, CustomView {
  
  @IBOutlet weak var customLabel: UILabel! 
  @IBoutlet weak var customButton: UIButton!
  
  //presenter
  var presenter: CustomPresenter! 
  
  override func viewDidLoad() {
    super.viewDidLoad()
    customButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
  }
  
  @objc func buttonDidTapped() {
    self.presenter.showView()
  }
  func setCustomView(custom: String) {
    self.customLabel.text = custom
  }
}

위와 같이 View는 Presenter을 가지고 있습니다. Presenter은 action, 데이터 갱신, 상태에 따라 View를 갱신해주어야 합니다. ViewController은 action이 들어오면 buttonDidTapped 메소드를 이용하여 Presenter에 정보를 넘깁니다. 그로인해 Presenter은 Model에서 데이터를 가져와 View를 갱신하는 메소드를 호출하는 방식입니다.

profile
iOS를 공부하고 있습니다.🔥

0개의 댓글