不要用retainCount來獲得對象的引用次數

這是一個CocoaChina上面的問題。就是爲什麼retainCount返回的對象引用值總是跟預期的不一樣呢?

這個應該是像我這樣初學者一般都會有的疑問,來看下面的一段例子

NSAlert *alert = [[NSAlert alloc] init];
    [alert setMessageText:@"TEST"];
    [alert setAlertStyle:NSWarningAlertStyle];
    [alert runModal];
    NSLog(@"alert has %lu retainCount",[alert retainCount]);
    [alert release];

結果log裏面始終報告retainCount是3。確實很讓人費解。(如果你是用別的類做的實驗,結果還會更奇怪)經過一番搜索,最後在StackOverFlow找到了解釋合理的答案:

Typically there should be no reason to explicitly ask an object what its retain count is (see retainCount). The result is often misleading, as you may be unaware of what framework objects have retained an object in which you are interested. In debugging memory management issues, you should be concerned only with ensuring that your code adheres to the ownership rules.
原文:http://stackoverflow.com/questions/2640568/objectivec-how-to-get-the-reference-count-of-an-nsobject
翻譯:通 常我們沒有必要去特地查詢一個對象的retain count是多少。查詢的結果常常會出乎意料。你不清楚framework裏面的其他對象對你感興趣的這個對象進行了多少retain操作。在debug 內存管理的問題時候,你只要關注保證你的代碼符合所有者規則即可。(譯者:我覺得應該是誰申請(幾次)誰釋放(幾次)原則)

因此在引用計數的內存管理方式裏面,我們可以把alloc, retain, copy, new, mutableCopy看作是+1操作。而通常根據原則,你要負責在適當的時候執行-1操作以保證沒有內存泄漏。


IOS超級羣,43146334


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章