짧은인사, 하루의 사건, 나의 행동
흐 마지막으로 TIL을 작성한지가 언제지... Zzz ㅋㅌ 그동안 공부를 조금 소홀히 하긴 했지만 하루도 안한적은 옶습니다!!(주말 제외)
그.. 유데미의 엘런님 강의를 듣고 따라하고 다시보느라 TIL을 작성하는 시간이 없었네요!!
하지만~~ 이강의도 거의 끝나가니 패캠에서 새로운 강의를 구매해서 보는중입니다!!
앨런님의 강의는 UIkit 이지만 패캠 강의는 스유라는 사쉴 굉장히 익숙하지 않지만 UIkit보단 접근하기
편한것,,,, 같기도,,?? 아닌가~~
델리게이트 패턴에 대해서 한번 정리 하고자 왔습니다!~
(10/14에 밴드 공연을 해서 이번주와 다음주는 조금 바쁠 예정인것 같네요.. 그래도 짬내서 해야지...)
뭐라도 해야지.....
배운점
UITableViewDataSource, UITableViewDelegate를 사용했지만 정확하게 이해를 하진 못하고 사용을 해왔습니다..
항상 아는 듯 모르는 듯한 Delegate Pattern을 공부 해보도록 하겠습니다..
Delegation
위임은 클래스 또는 구조체가 책임의 일부를 다른 타입의 인스턴스에 넘겨주거나 위임할 수 있도록 하는 디잔인 패턴입니다.
이 디자인 패턴은 위임된 기능을 제공하기 위해 준수하느느 타입이 보장되도록 위임된 책임을 캡슐화 하는 프로토콜을 정의하여 구현합니다.
예제를 보면서 이해하겠습니다!
protocol DiceGame {
var dice: Dice { get }
func play()
}
protocol DiceGameDelegate: AnyObject {
func gameDidStart(_ game: DiceGame)
func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int)
func gameDidEnd(_ game: DiceGame)
}
DiceGame 프로토콜은 dice변수와 play라는 함수를 가집니다. 주사위와 관련된 모든 게임에서 채택될 수 있는 프로토콜 입니다.
프로토콜은 강력한 참조 순환을 방지하기 위해 위임자는 약한 참조로 선언됩니다.
//Example
weak var delegate: SecondViewControllerDelegate?
class SnakesAndLadders: DiceGame {
let finalSquare = 25
let dice = Dice(sides: 6, generator: LinearCongruentialGenerator())
var square = 0
var board: [Int]
init() {
board = Array(repeating: 0, count: finalSquare + 1)
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
}
weak var delegate: DiceGameDelegate?
func play() {
square = 0
delegate?.gameDidStart(self)
gameLoop: while square != finalSquare {
let diceRoll = dice.roll()
delegate?.game(self, didStartNewTurnWithDiceRoll: diceRoll)
switch square + diceRoll {
case finalSquare:
break gameLoop
case let newSquare where newSquare > finalSquare:
continue gameLoop
default:
square += diceRoll
square += board[square]
}
}
delegate?.gameDidEnd(self)
}
}
위의 코드는 Snake and Ladders의 게임 버전 입니다.
제가 이 보드게임은 처음이라... 코드만 확인 하겠슴다 ㅎㅎ
SnakesAndLadders의 클래스는 DiceGame의 프로토콜을 채택 합니다. 상속으로 표시됩니다.
weak var delegate: DiceGameDelegate?
위에서 말했듯이 강력한 참조 순환을 방지하기 위해 위임자는 약한 참조로 선언됩니다.
프로토콜을 준수하기 위해 dice프로퍼티와 play() 메서드를 제공합니다.
class DiceGameTracker: DiceGameDelegate {
var numberOfTurns = 0
func gameDidStart(_ game: DiceGame) {
numberOfTurns = 0
if game is SnakesAndLadders {
print("Started a new game of Snakes and Ladders")
}
print("The game is using a \(game.dice.sides)-sided dice")
}
func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) {
numberOfTurns += 1
print("Rolled a \(diceRoll)")
}
func gameDidEnd(_ game: DiceGame) {
print("The game lasted for \(numberOfTurns) turns")
}
}
위의 예제는 DiceGameTracker클래스가 DIceGameDelegate 프로토콜을 채택합니다.
......계속 Document를 읽는데 무언가 확 와닿게 이해가 되지 않았습니다..
개발 블로그를 참고하여 이해를 도왔습니다 ㅎㅎ
Delegate pattern??
"객체가 자신의 책임을 다른 객체에게 위임 하는 디자인 패턴"
그럼 왜 "위임"을 하는거지??
UI의 Delegate Pattern
// Delegate Protocol
protocol UITableViewDelegate: AnyObject {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
}
// Delegating Object
class UITableView {
weak var delegate: UITableViewDelegate?
func didSelectedRowAt(indexPath: IndexPath) {
delegate?.tableView(self, didSelectRowAt: indexPath)
}
}
// Delegate Object
class ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(indexPath)
}
}
UITableView의 내부 코드를 수정할 수 없기에 다른 객체에게 위임을 하는 것이다!!
셀이 탭되었을때 어떤 행동을 할지는 상황마다 다르기에 개발자가 코드를 작성한다. 하지만 숨겨진 TableView의 코드를
수정할 수 없기에 다른 객체에게 해당 코드를 작성한 뒤, TableView가 그 객체의 코드를 호출해줘야 한다.
이 때 테이블 뷰와 객체를 연결해주는 방식이 DelegatePattern이다!!
Delegate Pattern의 핵심은 두 객체를 연결하는 것, 두개의 객체가 효율적으로 소통하도록 도와주는 것이다!
생각과 감정
많이 쓰던 내용인 Delegate를 깊게 들어가보진 않았지만,, 이제야 깨닫네요 하하.. Document는 저랑 맞지 않는건지 아직 이해가 완벽히 되지 않는것인진 몰겠지만,, 한국인이 정리한 개발블로그 너무 감사드립니다... 으아ㅏ.... 덕분에 이해가 잘됐습니다!!
앞으로의 계획선언
앞으로의 계획 ㅋ 살아남아야한다....
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/protocols/
Documentation
docs.swift.org
[iOS] Delegate 패턴을 이해해보자
Delegate v.(권한업무 등을) 위임하다
velog.io
'TIL' 카테고리의 다른 글
TIL_20231113 (0) | 2023.11.13 |
---|---|
TIL_20231107 (0) | 2023.11.07 |
TIL_20230921 (0) | 2023.09.21 |
TIL_20230918 (0) | 2023.09.18 |
TIL_20230914 (0) | 2023.09.14 |