[Swift๐Ÿฆฉ] #15 ์ดˆ๊ธฐํ™” ํ•ด์ œ (Deinitialization)

๋˜์ƒยท2022๋…„ 3์›” 31์ผ
0

iOS

๋ชฉ๋ก ๋ณด๊ธฐ
28/42
post-thumbnail
  • ์ดˆ๊ธฐํ™” ํ•ด์ œ ๊ตฌ๋ฌธ
    • ํด๋ž˜์Šค ์ธ์Šคํ„ด์Šค๊ฐ€ ํ• ๋‹น ํ•ด์ œ๋˜๊ธฐ ์ง์ „์— ํ˜ธ์ถœ๋œ๋‹ค.
    • deinit ํ‚ค์›Œ๋“œ๋กœ ์ž‘์„ฑ.
    • ํด๋ž˜์Šค ํƒ€์ž…์—์„œ๋งŒ ๊ฐ€๋Šฅ!!

Deinit ์˜ ์ž‘๋™

  • Swift ๋Š” ์ž๋™ ์ฐธ์กฐ ์นด์šดํŒ… (ARC) ๋ฅผ ํ†ตํ•ด์„œ ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ๊ด€๋ฆฌํ•œ๋‹ค.
  • ๋” ์ด์ƒ ํ•„์š”ํ•˜์ง€ ์•Š์•„์ง„(์ฐธ์กฐ ์นด์šดํŠธ๊ฐ€ 0์ธ) ์ธ์Šคํ„ด์Šค๋ฅผ ๋ฉ”๋ชจ๋ฆฌ์—์„œ ํ•ด์ œํ•˜๋Š” ๊ฒƒ.
  • ์ž๋™์œผ๋กœ ๋˜๊ธฐ ๋•Œ๋ฌธ์—, C์ฒ˜๋Ÿผ free(in_degree) ์ด๋ ‡๊ฒŒ ํ•  ํ•„์š”๊ฐ€ ์—†์ง€๋งŒ,
  • ํ•˜์ง€๋งŒ ์ž์ฒด ์ž์›์œผ๋กœ ์ž‘์—…ํ•˜๋Š” ๊ฒฝ์šฐ, ์ง์ ‘ ์ˆ˜ํ–‰ํ•ด์ค˜์•ผํ•  ๋•Œ๊ฐ€ ์žˆ๋‹ค. (๋ช…์‹œ์ ์œผ๋กœ ํ•˜๊ธฐ ์œ„ํ•ด์„œ ์‚ฌ์šฉํ•˜๊ธฐ๋„ ํ•จ)
// ํŒŒ๋ผ๋ฏธํ„ฐ ์—†๊ณ , ์†Œ๊ด„ํ˜ธ๋„ ์—†์Œ.
deinit {
    // perform the deinitialization
    var_a = nil
}
  • ์ธ์Šคํ„ด์Šค ํ• ๋‹น ํ•ด์ œ ์ง์ „์— ์ž๋™์œผ๋กœ ํ˜ธ์ถœ๋˜๊ณ , ์ง์ ‘ ํ˜ธ์ถœํ•˜๋Š” ๊ฒƒ์€ ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค.
  • ์ƒ์œ„ ํด๋ž˜์Šค์˜ deinit ์€ ํ•˜์œ„ ํด๋ž˜์Šค๋กœ ์ƒ์†๋œ๋‹ค.
  • ํ•˜์œ„ ํด๋ž˜์Šค์˜ deinit ํ˜ธ์ถœ์ด ๋๋‚  ๋•Œ, ์ž๋™์œผ๋กœ ์ƒ์œ„ ํด๋ž˜์Šค์˜ deinit ์„ ํ˜ธ์ถœํ•œ๋‹ค.
  • ์ƒ์œ„ ํด๋ž˜์Šค์˜ deinit ์€ ํ•˜์œ„ ํด๋ž˜์Šค์˜ deinit ๊ตฌํ˜„์ด ์—†์–ด๋„ ํ•ญ์ƒ ํ˜ธ์ถœ๋œ๋‹ค.



Deinit ์ž‘๋™ ์˜ˆ์‹œ

class Bank {
    static var coinsInBank = 10_000
    static func distribute(coins numberOfCoinsRequested: Int) -> Int {
        let numberOfCoinsToVend = min(numberOfCoinsRequested, coinsInBank)
        coinsInBank -= numberOfCoinsToVend
        return numberOfCoinsToVend
    }
    static func receive(coins: Int) {
        coinsInBank += coins
    }
}

class Player {
    var coinsInPurse: Int
    init(coins: Int) {
        coinsInPurse = Bank.distribute(coins: coins)
    }
    func win(coins: Int) {
        coinsInPurse += Bank.distribute(coins: coins)
    }
    
    // player instance ๊ฐ€ ํ• ๋‹น ํ•ด์ œ๋  ๋•Œ,
    // Bank ์˜ type method receive ํ˜ธ์ถœ.
    deinit {
        Bank.receive(coins: coinsInPurse)
    }
}

var playerOne: Player? = Player(coins: 100) // player 100, bank 9900
playerOne!.win(coins: 2_000) // player 2100, bank 8800
playerOne = nil // bank 10000
profile
0๋…„์ฐจ iOS ๊ฐœ๋ฐœ์ž์ž…๋‹ˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€