2011-05-02 57 views
3

如果我在函數內部創建一個對象並返回它,何時應該釋放這個對象?這裏是我創建一個對象的例子。發佈對象正確返回?

- (NSDictionary*) sampleFunction 
{ 
    NSMutableDictionary* state = [[NSMutableDictionary alloc] initWithCapacity:5]; 

    [state setObject:[[NSNumber alloc] initWithInt:self.a] forKey:@"a"]; 
    [state setObject:[[NSNumber alloc] initWithInt:self.b] forKey:@"b"]; 
    [state setObject:[[NSNumber alloc] initWithInt:self.c] forKey:@"c"]; 

    return state; 
} 

附加問題:爲了避免內存泄漏,我也應該釋放這裏分配的NSNumbers?這段代碼看起來像沒有內存泄漏?

回答

1

首先,你應該去這個指南的所有規則:

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html

...不要把人放在這裏作爲福音說什麼。我上面鏈接的指南中會列出一些例外情況和奇怪的規則。

現在,與你的例子有關:廣泛地說來說,每次你都必須發佈它alloc。當你從一個方法返回一個值時,它應該是autoreleased(99%的時間,有幾個例外:看,沒有什麼是容易的!)。蘋果提供了一些方便的自動發佈方法 - NSNumber有其中之一。

我會向你展示你上面的代碼,但改寫爲使用這些自動釋放方法:

- (NSDictionary*) sampleFunction 
{ 
    NSMutableDictionary* state = [NSMutableDictionary dictionaryWithCapacity:5]; 

    [state setObject:[NSNumber numberWithInt:self.a] forKey:@"a"]; 
    [state setObject:[NSNumber numberWithInt:self.b] forKey:@"b"]; 
    [state setObject:[NSNumber numberWithInt:self.c] forKey:@"c"]; 

    return state; 
} 

正如我提到的,你也可以使用autoreleasealloc/init

NSMutableDictionary* state = [[[NSMutableDictionary alloc] initWithCapacity:5]autorelease]; 

再次,我上面鏈接的Apple文檔是要回答內存管理問題的地方。

+0

這非常有幫助,謝謝。 – Mark 2011-05-02 10:05:15