Skip to content

Latest commit

ย 

History

History
66 lines (50 loc) ยท 1.93 KB

Reference-count-in-ARC.md

File metadata and controls

66 lines (50 loc) ยท 1.93 KB

Retain Count ๋ฐฉ์‹์— ๋Œ€ํ•ด ์„ค๋ช…ํ•˜์‹œ์˜ค.

์ฐธ๊ณ ํ•œ ์ข‹์€ ๊ธ€

Answer

ARC๋Š” compile time์— ์ž๋™์œผ๋กœ retain, release ๋ฉ”์„œ๋“œ๋ฅผ ์ ์ ˆํ•œ ์œ„์น˜์— ์‚ฝ์ž…ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๋™์ž‘ํ•ฉ๋‹ˆ๋‹ค.

์ด๋Ÿฐ์‹์œผ๋กœ complie time์— ์‚ฝ์ž…์ด ์ด๋ฃจ์–ด์ง€๋ฉด, runtime๋•Œ ์ธ์Šคํ„ด์Šค์˜ ์ƒ์„ฑ, ์ฐธ์กฐ๊ฐ€ ์ผ์–ด๋‚  ๋•Œ ๋งˆ๋‹ค ๋ฉ”์„œ๋“œ๊ฐ€ ์‹คํ–‰๋˜๋ฉฐ ์ž๋™์œผ๋กœ Retain Count๊ฐ€ ์ด๋ฃจ์–ด์ง€๋Š” ๋ฐฉ์‹์ž…๋‹ˆ๋‹ค. ๊ทธ๋Ÿฌ๋‹ค๊ฐ€ Count๊ฐ€ 0์ด ๋˜๋ฉด deinit์„ ํ†ตํ•ด ๋ฉ”๋ชจ๋ฆฌ๊ฐ€ ํ•ด์ œ๋ฉ๋‹ˆ๋‹ค.

Retain Count(RC)๋Š” ์ธ์Šคํ„ด์Šค์˜ ์ƒ์„ฑ ์‹œ +1์ด ๋˜๊ณ  ํ•ด๋‹น ์ธ์Šคํ„ด์Šค๊ฐ€ ์ฐธ์กฐ๋  ๋•Œ +1์ด ๋ฉ๋‹ˆ๋‹ค. ๋ฐ˜๋Œ€๋กœ ์ฐธ์กฐ๊ฐ€ ํ•ด์ œ๋˜๋ฉด -1์ด ๋ฉ๋‹ˆ๋‹ค.

strong์ด ์•„๋‹ˆ๋ผ weak์œผ๋กœ ์ฐธ์กฐํ•  ๊ฒฝ์šฐ RC๋Š” ์ฆ๊ฐ€ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

์‹ค์Šต

ํด๋ž˜์Šค์˜ ์ธ์Šคํ„ด์Šค๊ฐ€ ์ƒ์„ฑ๋  ๋•Œ์™€ ํ•ด์ง€๋  ๋•Œ ๋กœ๊ทธ ์ถœ๋ ฅ

class Person {
    let name: String
    init(name: String) {
        self.name = name
        print("\(name) is being initialized")
    }
    deinit {
        print("\(name) is being deinitialized")
    }
}

3๊ฐœ์˜ ๋ณ€์ˆ˜ ๋ชจ๋‘ ์˜ต์…”๋„ => ์ดˆ๊ธฐ๊ฐ’ nil

var reference1: Person?
var reference2: Person?
var reference3: Person?

Person ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ, RC = 1

reference1 = Person(name: "John Appleseed")
// Prints "John Appleseed is being initialized"

Person ์ธ์Šคํ„ด์Šค RC = 3

reference2 = reference1
reference3 = reference1

Person ์ธ์Šคํ„ด์Šค RC = 1

reference1 = nil
reference2 = nil

Person ์ธ์Šคํ„ด์Šค RC = 0, ๋ฉ”๋ชจ๋ฆฌ ํ•ด์ง€

reference3 = nil
// Prints "John Appleseed is being deinitialized"