我有點迷路了內存管理。我讀過,你應該釋放,只要你分配。但是當你得到一個沒有alloc的實例時,你不應該發佈。iPhone內存管理
這情況怎麼樣,只需要知道如果我編碼正確。我還是iphone開發新手。
我有一個類CustomerRepository它有一個方法
- (MSMutableArray *) GetAllCustomers() {
MSMutableArray *customers = [[MSMutableArray alloc] init];
Customer *cust1 = [[Customer alloc] init];
cust1.name = @"John";
Customer *cust2 = [[Customer alloc] init];
cust2.name = @"Tony";
[customers addOjbect:cust1];
[customers addOjbect:cust2];
[cust1 release];
[cust2 release];
return customers;
}
然後,我有一個UIViewController
- (void) LoadCustomers() {
CustomerRepository *repo = [[CustomerRepository alloc] init];
MSMutableArray *customers = [repo GetAllCustomers];
// Iterate through all customers and do something
[repo release];
}
因此,在這種情況下...的MSMutableArray永遠不會釋放?它應該放在哪裏?
我讀過的地方autorelease是不是太好,無法在iPhone上使用。但在我的情況下,我真的別無選擇,只能autorelease(這是垃圾收集正確)?在我的GetAllCustomers方法中返回autorelease更好嗎?或者只是讓repo創建數組,但LoadCustomer方法在完成時釋放它? – pdiddy 2010-10-21 17:34:03
你讀過關於autorelease的內容絕對不對。閱讀Apple的內存管理指南。它可能需要一兩天才能閱讀,但會爲您節省很多災難。在這種情況下,你應該在GetAllCustomers方法中自動釋放,因爲方法名並不意味着調用者將擁有返回的對象。 – taskinoor 2010-10-22 04:33:53