๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป iOSun
article thumbnail

swift์—์„  ์ฐธ์กฐ ํšŸ์ˆ˜๋ฅผ ์„ธ๋Š” ARC๋กœ ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ๊ด€๋ฆฌํ•œ๋‹ค.

 

์ฐธ์กฐ ํšŸ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•˜๋Š” ๋ฒ•์€

 

์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑ or ๊ธฐ์กด ์ธ์Šคํ„ด์Šค๋ฅผ ๋‹ค๋ฅธ ๋ณ€์ˆ˜์— ๋Œ€์ž…ํ•  ๋•Œ +1

์ธ์Šคํ„ด์Šค๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋˜ ๋ณ€์ˆ˜๊ฐ€ ํ•ด์ œ๋  ๋•Œ or nil์ด ๋  ๋•Œ -1

 

๊ทธ๋ฆฌ๊ณ  0์ด ๋˜์—ˆ์„ ๋•Œ, ๋ฉ”๋ชจ๋ฆฌ์—์„œ ์ž๋™์œผ๋กœ ํ•ด์ œ๊ฐ€ ๋œ๋‹ค.

 

์ด๋ก ์ ์œผ๋ก  ์ด๋ ‡๊ณ ,, ์‹ค์ œ๋กœ CFGetRetainCount ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉฐ ์ฐธ์กฐ ํšŸ์ˆ˜๋ฅผ ์„ธ์–ด๋ณด์ž.

 

 

RC +1์ด ๋˜๋Š” ๊ฒฝ์šฐ

class EmptyClass {
    
}

let myClass = EmptyClass() // RC +1
let myClass2 = myClass // RC +1
let myClass3 = myClass // RC +1

print(CFGetRetainCount(myClass)) // 4
print(CFGetRetainCount(myClass2)) // 4
print(CFGetRetainCount(myClass3)) // 4

 

myClass ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ด์ค„ ๋•Œ -> +1

myClass ๊ฐ์ฒด๊ฐ€ myClass2 ๋ณ€์ˆ˜์— ๋Œ€์ž… -> +1

myClass ๊ฐ์ฒด๊ฐ€ myClass3 ๋ณ€์ˆ˜์— ๋Œ€์ž… -> +1

 

ํ•ด์„œ 3์ด ์ฐํž ๊ฒƒ ๊ฐ™์•˜์œผ๋‚˜,, 4๊ฐ€ ์ฐํ˜”๋‹ค.

 

(์ฐพ์•„๋ณด๋‹ˆ CFGetRetainCount ํ•จ์ˆ˜๊ฐ€ ํ˜ธ์ถœ๋˜๋ฉด ์ฐธ์กฐ ํšŸ์ˆ˜๊ฐ€ +1์ด ๋œ๋‹ค๊ณ  ํ•œ๋‹ค. ์•„๋งˆ ์ฒ˜์Œ CFGetRetainCount๊ฐ€ ํ˜ธ์ถœ๋  ๋•Œ๋งŒ +1์ด ๋˜์–ด์„œ ์ธ๊ฒƒ ๊ฐ™๋‹ค๋ผ๋Š” ์ถ”์ธก,, (์ฐธ๊ณ ))

 

 

class EmptyClass {

}

class MyClass {
    let class1 = EmptyClass()
    let class2 = EmptyClass()
}

let myClass = MyClass() // RC +1
let myClass2 = myClass // RC +1
let myClass3 = myClass // RC +1

print(CFGetRetainCount(myClass.class1)) // 2
print(CFGetRetainCount(myClass2.class2)) // 2

 

๋‹ค์‹œ MyClass๋ผ๋Š” ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค๊ณ  myClass ๋‚ด๋ถ€์— class1, class2๋ฅผ ์ถœ๋ ฅํ•ด ๋ณด์•˜๋‹ค.

myClass ์ž์ฒด์˜ RC๋Š” 4์ด๊ฒ ์ง€๋งŒ ๋‚ด๋ถ€์˜ class1, class2 ์˜ RC๋Š” ๊ฐ๊ฐ 2๋ฅผ ๊ฐ–๋Š” ๊ฑธ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.

 

 

RC -1์ด ๋˜๋Š” ๊ฒฝ์šฐ

class MyClass {
    let class1 = EmptyClass()
    let class2 = EmptyClass()
}

let myClass = MyClass() // RC +1
var myClass2: MyClass? = myClass // RC +1
var myClass3: MyClass? = myClass // RC +1

print(CFGetRetainCount(myClass)) // 4
myClass2 = nil // RC -1
print(CFGetRetainCount(myClass)) // 3
myClass3 = nil // RC -1
print(CFGetRetainCount(myClass)) // 2

 

nil์ด ๋  ๋•Œ์—๋„ RC๊ฐ€ -1์ด ๋˜๋Š” ๊ฑธ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

 

๊ตฌ์กฐ์ฒด์˜ RC?

๊ทธ๋ ‡๋‹ค๋ฉด ๊ฐ’ ํƒ€์ž…์ธ sturct์˜ ์ฐธ์กฐ ํšŸ์ˆ˜๋„ ์ฐํž๊นŒ?

๊ธฐ๋ณธ์ ์œผ๋กœ ARC๋Š” ์ฐธ์กฐ ํƒ€์ž…์— ํ•œํ•ด์„œ๋งŒ ๋ฉ”๋ชจ๋ฆฌ ๊ด€๋ฆฌ๋ฅผ ํ•œ๋‹ค. (๊ฐ’ ํƒ€์ž…์€ ๊ฐ’์„ ๋ณต์‚ฌํ•ด์„œ ๋‹ค๋ฅธ ์ฃผ์†Œ๊ฐ’์„ ๊ฐ€์ง€๊ธฐ ๋•Œ๋ฌธ์— ์˜๋ฏธ๊ฐ€ ์—†๊ธฐ ๋•Œ๋ฌธ)

 

 

0์ด ๋œฐ๊ฑฐ๋ผ๊ณ  ์ถ”์ธกํ–ˆ๋Š”๋ฐ,, ํด๋ž˜์Šค์˜ ์ธ์Šคํ„ด์Šค๋งŒ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ๋ฐ›์„ ์ˆ˜ ์žˆ์–ด ์ปดํŒŒ์ผ ์—๋Ÿฌ๊ฐ€ ๋–ด๋‹ค. 

ํ•จ์ˆ˜ ๋งค๊ฐœ๋ณ€์ˆ˜ ํƒ€์ž…์„ ๋ณด๋‹ˆ AnyObject์ด๊ธฐ ๋•Œ๋ฌธ์— ํด๋ž˜์Šค์˜ ์ธ์Šคํ„ด์Šค๋งŒ ์ฐธ์กฐ ํšŸ์ˆ˜๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค.

profile

๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป iOSun

@iosun

ํฌ์ŠคํŒ…์ด ์ข‹์•˜๋‹ค๋ฉด "์ข‹์•„์š”โค๏ธ" ๋˜๋Š” "๊ตฌ๋…๐Ÿ‘๐Ÿป" ํ•ด์ฃผ์„ธ์š”!

profile on loading

Loading...