2010-11-09 18 views
0

我只是在學習Objective C,所以我可能錯過了一些東西,但下面的代碼是泄漏,對吧?蘋果文檔中的目標c內存泄漏?

apple's docs摘自:

- (NSString*) title { 
    return [[title retain] autorelease]; 
} 

- (void) setTitle: (NSString*) newTitle { 
    if (title != newTitle) { 
     [title release]; 
     title = [newTitle retain]; // Or copy, depending on your needs. 
    } 
} 

吸氣劑保持和自動釋放(相互抵消),但設定器還保留。這會阻止引用計數達到0,對吧?我錯過了什麼?

回答

2

你缺少的東西(因爲它在示例中沒有顯示)是對於對象的dealloc方法中的所有保留屬性將會有release

+0

那麼,爲什麼不只是從getter返回標題呢?意思是,消除保留/自動釋放? – 2010-11-09 13:36:22

+0

沒關係,在這裏回答:http://stackoverflow.com/questions/801828/why-should-a-self-implemented-getter-retain-and-autorelease-the-returned-object – 2010-11-09 13:37:23

0

啊,如果我的文檔中讀得更遠,蘋果解釋說:

由於對象從get訪問在當前範圍自動釋放返回,如果屬性值更改

它仍然有效

保留/ autorelease在setter在getter之後被調用時非常有用,因爲setter釋放了舊值。