Skip to content

Latest commit

ย 

History

History
98 lines (66 loc) ยท 3.27 KB

MRC.md

File metadata and controls

98 lines (66 loc) ยท 3.27 KB

ARC ๋Œ€์‹  Manual Reference Count ๋ฐฉ์‹์œผ๋กœ ๊ตฌํ˜„ํ•  ๋•Œ ๊ผญ ์‚ฌ์šฉํ•ด์•ผ ํ•˜๋Š” ๋ฉ”์„œ๋“œ๋“ค์„ ์“ฐ๊ณ  ์—ญํ• ์„ ์„ค๋ช…ํ•˜์‹œ์˜ค.

์ฐธ๊ณ ํ•œ ์‚ฌ์ดํŠธ

์‚ฌ์ „์ง€์‹

  • ARC: Automatic Reference Counting
  • MRC: Manual Reference Counting

Anwser

MRC(Manual Reference Counting)๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ์—๋Š” retain, release ๋ฉ”์„œ๋“œ๋ฅผ ๊ผญ ์‚ฌ์šฉํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค.

MRC๋ฅผ retain/release ๊ฐœ๋…์œผ๋กœ ์ƒ๊ฐํ•ด์„œ MRR(Memory Retain Release)๋ผ๊ณ ๋„ ๋ถ€๋ฆ„

  • retain: retain count(=reference count)์ฆ๊ฐ€๋ฅผ ํ†ตํ•ด ํ˜„์žฌ Scope์—์„œ ๊ฐ์ฒด๊ฐ€ ์œ ์ง€๋˜๋Š” ๊ฒƒ์„ ๋ณด์žฅ

    • [test retain];
    • ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ ์‹œ์—๋Š” ์ž๋™์œผ๋กœ count +1์ด ๋˜์ง€๋งŒ ๊ทธ ์ดํ›„๋ถ€ํ„ฐ ์ธ์Šคํ„ด์Šค์˜ ์ฃผ์†Œ๊ฐ’์„ ํ• ๋‹น๋ฐ›์€ ๊ฒฝ์šฐ์—๋Š” retain๋ฉ”์„œ๋“œ๋ฅผ ํ†ตํ•ด ์ˆ˜๋™์ ์œผ๋กœ RC๋ฅผ ์˜ฌ๋ ค์ฃผ๋Š” ์ž‘์—…์„ ํ•ด์ฃผ์–ด์•ผ ํ•จ
  • release: retain count(=reference count)๋ฅผ ๊ฐ์†Œ์‹œํ‚ด. retain ํ›„์— ํ•„์š” ์—†์„ ๋•Œ releaseํ•จ

    • [test2 release];
    • ARC์—์„œ ํ–ˆ๋˜๊ฒƒ์ฒ˜๋Ÿผ test2๋ฅผ ๋”์ด์ƒ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•„์„œ nil์„ ๋Œ€์ž…ํ•˜๋”๋ผ๋„ ์ž๋™์œผ๋กœ RC๊ฐ€ 0์œผ๋กœ ํ•ด์ง€๋˜์ง€ ์•Š์Œ. release ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•ด์•ผ RC๊ฐ’์„ ๊ฐ์†Œ์‹œํ‚ฌ ์ˆ˜ ์žˆ์Œ

๋” ๊นŠ๊ฒŒ ์•Œ์•„๋ณด๊ธฐ

retain

  1. ์ƒˆ๋กœ ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•  ๊ฒฝ์šฐ

์ด๋•Œ๋Š” MRC์—ฌ๋„ RC๊ฐ€ ์ž๋™์œผ๋กœ +1 ๋œ๋‹ค.

// test๋ผ๋Š” ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ
TestClass *test [[TestClass alloc] init];

/* 
test.retainCount == 1 
*/

  1. ๊ธฐ์กด ์ธ์Šคํ„ด์Šค๋ฅผ ์ฐธ์กฐํ•  ๊ฒฝ์šฐ์—๋Š”?

test2์—์„œ ๊ธฐ์กด ์ธ์Šคํ„ด์Šค(test)๋ฅผ ์ฐธ์กฐ

ARC์˜ ๊ฒฝ์šฐ์—๋Š” ์ž๋™์œผ๋กœ RC๊ฐ€ +1 ๋์Œ

TestClass *test [[TestClass alloc] init];
TestClass *test2 = test;

// test.retainCount == 1 

ํ•˜์ง€๋งŒ MRC๋Š” ์ˆ˜๋™์œผ๋กœ retain์„ ํ•ด์ฃผ์ง€ ์•Š์•˜๊ธฐ ๋•Œ๋ฌธ์— ์•„์ง RC๊ฐ€ ์ฆ๊ฐ€๋˜์ง€ ์•Š๋Š”๋‹ค.

์ด๋ ‡๊ฒŒ retain ์„ ์ˆ˜๋™์œผ๋กœ ํ•ด์ฃผ์–ด์•ผ retain count๊ฐ€ ์ฆ๊ฐ€ํ•œ๋‹ค.

TestClass *test [[TestClass alloc] init];
TestClass *test2 = [test retain];
 
//test.retainCount == 2

release

  1. test2๋ฅผ ๋”์ด์ƒ ์‚ฌ์šฉํ•˜์ง€ ์•Š์„๊ฑฐ์•ผ ARC์ฒ˜๋Ÿผ nil์„ ๋Œ€์ž…ํ•ด๋ณผ๊นŒ?
TestClass *test [[TestClass alloc] init];
TestClass *test2 = [test retain];
test2 = nil;
 
//test.retainCount == 2

์•ˆ๋œ๋‹ค. ์ˆ˜๋™์œผ๋กœ release๋ฅผ ํ•ด์ฃผ์ง€ ์•Š์œผ๋ฉด RC๋Š” ๋‚ด๋ ค๊ฐ€์ง€ ์•Š๋Š”๋‹ค.

TestClass *test [[TestClass alloc] init];
TestClass *test2 = [test retain];
[test2 release]; // test.retainCount == 1
test2 = nil; // test2.retainCount == 0

[test2 release];๋ฅผ ํ•ด์คŒ์œผ๋กœ์จ test์˜ RC๋Š” 1๊ฐ์†Œํ•˜๊ณ  ์ฐธ์กฐํ•˜๊ณ  ์žˆ๋Š” ์ธ์Šคํ„ด์Šค๊ฐ€ ์—†๋Š” test2๋Š” ๊ทธ์ œ์„œ์•ผ nil์„ ๋Œ€์ž…ํ•˜์—ฌ 0์ž„์„ ๋ช…์‹œํ•ด ์ค„ ์ˆ˜ ์žˆ๋‹ค.