作者huggie (huggie)
看板MacDev
標題Re: [問題] 關於memory management的問題
時間Tue Jul 7 16:44:07 2009
※ 引述《angelyin (等待.微笑)》之銘言:
: 各位前輩大家好
: 最近開始研究objective-c
: 想寫跟iPhone有關的程式
: 在記憶體管理方面碰到了以下的問題
: main.n的部分程式碼如下:
: int main(int argc, char *argv[])
: {
: NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
: NSString *str1 = @" string1!";
: NSString *str2 = [NSString stringWithString: @" string2!"];
: printf("str1 retain count: %x\n", [str1 retainCount]);
: printf("str2 retain count: %x\n", [str2 retainCount]);
: ......
: }
: output:
: str1 retain count:7fffffff
: str2 retain count:7fffffff
: 我翻了書和網路上的文章
: output為
: str1 retain count:ffffffff
: str2 retain count:1
嗨我也是新手,根據 Programming in Objecitive-C 2.0 這本書說,
在 Leopard 之前 str2 會是 1, 之後就會是 unsigned int 的最大值。
因為 str2 這個 case 也是 immutable 的,所以在 Leopard 之後
compile 變聰明了把他 optimized 起來,字串還是使用同str1 的
string literal,就不用再 copy 一次。因此沒有 reference count。
而在 Leopard 之前是 runtime 的時候再 allocate 在 stack 上面,
非 string literal,因此就有 reference count。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.129.160.62
※ 編輯: huggie 來自: 140.129.160.62 (07/07 16:45)
1F:→ huggie:我講錯了..應該不是 stack,應該是 heap 07/07 17:37
2F:推 angelyin:謝謝^^ 07/08 17:18