ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Weak Reference - Memory
    iOS/๐ŸŸ  Swift 2021. 1. 2. 20:48

    " ์•ฝํ•œ ์ฐธ์กฐ "

     

    ๊ฐ•ํ•œ ์ฐธ์กฐ ์ˆœํ™˜์„ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•œ ๋ฐฉ๋ฒ• ์ค‘ ํ•˜๋‚˜ ์ž…๋‹ˆ๋‹ค.

     

    ์ฐธ์กฐ ํƒ€์ž…์˜ ๋ณ€์ˆ˜์˜ ์„ ์–ธ ์•ž์— 'weak' ํ‚ค์›Œ๋“œ๋ฅผ ์จ์ฃผ์–ด์„œ ๊ตฌํ˜„ํ•ฉ๋‹ˆ๋‹ค.

     

    ๊ฐ•ํ•œ ์ฐธ์กฐ์™€ ๋‹ฌ๋ฆฌ ์•ฝํ•œ ์ฐธ์กฐ๋Š” ์ธ์Šคํ„ด์Šค๋ฅผ ์†Œ์œ  ( retain ) ํ•˜์ง€ ์•Š๊ณ  ์ฐธ์กฐ ( refer ) ๋งŒ ํ•ฉ๋‹ˆ๋‹ค.

     

    ๋”ฐ๋ผ์„œ  ARC ๋ชจ๋ธ์˜ reference counting์„ ์ฆ๊ฐ€์‹œํ‚ค์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

     

    ๋˜ํ•œ ๋„์ค‘์— reference counting์ด 0 ์ด ๋˜์–ด ์ฐธ์กฐํ•˜๊ณ  ์žˆ๋˜ ์ธ์Šคํ„ด์Šค๊ฐ€ ๋ฉ”๋ชจ๋ฆฌ ํ•ด์ œ๋  ์ˆ˜ ์žˆ๋Š”๋ฐ, ์ด ๋•Œ๋Š” nil๋กœ ์ดˆ๊ธฐํ™” ๋ฉ๋‹ˆ๋‹ค.

     

    ๊ธฐ์กด์˜ ๊ฐ’์ด ๋ณ€๊ฒฝ๋˜์–ด์•ผ ํ•˜๊ธฐ ( instance ์ฃผ์†Œ - > nil )  ๋•Œ๋ฌธ์— ๋ณ€์ˆ˜ ( var ) ์—ฌ์•ผ ํ•˜๊ณ , nil์„ ๋‹ด์„ ์ˆ˜ ์žˆ์–ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์˜ต์…”๋„์ด์—ฌ์•ผ ํ•ฉ๋‹ˆ๋‹ค.

     

    ์ข…ํ•ฉ์ ์œผ๋กœ, weak ํ‚ค์›Œ๋“œ๋Š” ์˜ต์…”๋„ ์ฐธ์กฐ ํƒ€์ž…์˜ ๋ณ€์ˆ˜ ์•ž์—๋งŒ ์„ ์–ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค

     

    class Person {
        ...
        var room: Room?
        ...
    }
    
    class Room {
    	...
        weak var person: Person?
        ...
        deinit {
            print("deinit")
        }
    }
    
    var kim: Person? = Person() // Person Instance (์ดํ•˜ P.I) ์ฐธ์กฐ ํšŸ์ˆ˜ : 1
    var room: Room? = Room() // Room Instance (์ดํ•˜ R.I) ์ฐธ์กฐ ํšŸ์ˆ˜ : 1
    
    room?.person = kim // P.I ์ฐธ์กฐ ํšŸ์ˆ˜ : 1 ( ์•ฝํ•œ ์ฐธ์กฐ )
    kim?.room = room // R.I ์ฐธ์กฐ ํšŸ์ˆ˜ : 2
    
    kim = nil  // P.I ์ฐธ์กฐ ํšŸ์ˆ˜ : 0, R.I ์ฐธ์กฐ ํšŸ์ˆ˜ : 1
    room = nil // R.I ์ฐธ์กฐ ํšŸ์ˆ˜ : 0
    // "deinit"
    

     

    ์ถ”๊ฐ€์ ์œผ๋กœ, ๋ฉ”๋ชจ๋ฆฌ๊ฐ€ ํ•ด์ œ๋˜๋ฉด ์ธ์Šคํ„ด์Šค์˜ ํ”„๋กœํผํ‹ฐ๊ฐ€ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๊ฐ•ํ•œ ์ฐธ์กฐ (์—ฌ๊ธฐ์„œ๋Š” kim์˜ room ์ €์žฅ์†์„ฑ) ๋Š” ์‚ฌ๋ผ์ง‘๋‹ˆ๋‹ค. ์ด ๋•Œ reference counting์ด 1 ๊ฐ์†Œํ•ฉ๋‹ˆ๋‹ค.

     

     

     

     

    ๋.


     

    'iOS > ๐ŸŸ  Swift' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

    Initializers - Initializer  (0) 2021.01.05
    Strong Reference Cycle - Memory  (0) 2021.01.03
    [Swift] self ๋Š” ์–ด๋Š ์‹œ์ ๋ถ€ํ„ฐ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์„๊นŒ?  (2) 2021.01.01
    Strong Reference - Memory  (0) 2020.12.31
    ARC - Memory  (0) 2020.12.30

    ๋Œ“๊ธ€

์–ด์ œ๋ณด๋‹ค ๋ฐœ์ „ํ•œ ๋‚˜