2011-05-12 70 views
3

我想填充一個這樣的數組:自動釋放NSMutableArray裏沒有人煙

NSMutableArray *array = [self methodThatReturnsAnArray]; 

在「methodThatReturnsAnArray」 - 方法我創建一個這樣的數組:

NSMutableArray *arrayInMethod = [[NSMutableArray alloc] init]; 

當我完成填充「arrayInMethod」我正在返回數組,並且爲了防止我正在使用的內存泄漏:

return [arrayInMethod autorelease]; 

然而,「數組」變量永遠不會被填充。當刪除「autorelease」它雖然工作正常。我應該怎麼做才能確保我發佈的返回對象?

編輯

+ (NSMutableArray *)buildInstants:(NSArray *)huntsArray { 

    NSMutableArray *goGetObjects = [[[NSMutableArray alloc] init] autorelease]; 

    for (int i = 0; i < [huntsArray count]; i++) { 

     NSDictionary *huntDict = [huntsArray objectAtIndex:i]; 

     PHGoGet *goGet = [[PHGoGet alloc] init]; 

     goGet.title = [huntDict objectForKey:@"title"]; 
     goGet.description = [huntDict objectForKey:@"description"]; 
     goGet.start = [huntDict objectForKey:@"start"]; 
     goGet.end = [huntDict objectForKey:@"end"]; 
     goGet.ident = [huntDict objectForKey:@"id"]; 

     if ((CFNullRef)[huntDict objectForKey:@"image_url"] != kCFNull) { 

      goGet.imageURL = [huntDict objectForKey:@"image_url"]; 

     } else { 

      goGet.imageURL = nil; 
     } 

     if ((CFNullRef)[huntDict objectForKey:@"icon_url"] != kCFNull) { 

      goGet.iconURL = [huntDict objectForKey:@"icon_url"]; 

     } else { 

      goGet.iconURL = nil; 
     } 

     goGet.longitude = [huntDict objectForKey:@"lng"]; 
     goGet.latitude = [huntDict objectForKey:@"lat"]; 
     goGet.companyIdent = [huntDict objectForKey:@"company_id"]; 

     [goGetObjects insertObject:goGet atIndex:i]; 
     [goGet release]; 
    } 

    return [[goGetObjects copy] autorelease]; 
} 
+3

刪除'autorelease'應該不會有任何區別,至少不會立即。你可以在'methodThatReturnsAnArray'中發佈其餘的代碼嗎? – kubi 2011-05-12 16:45:36

+2

你在哪裏檢查數組沒有填充?返回後或稍後(可能來自按鈕處理程序)? – taskinoor 2011-05-12 16:51:56

+0

@kubi現在我已經添加了一些代碼 – 2011-05-13 08:53:20

回答

1

嘗試使用convienence方法NSMutableArray ...變化:

NSMutableArray *arrayInMethod = [[NSMutableArray alloc] init]; 

要...

NSMutableArray *arrayInMethod = [NSMutableArray array]; 

array將返回一個autoreleased對象。

+0

他們實際上被稱爲'工廠'方法。 – 2011-05-12 17:00:52

+3

我一直聽到他們稱爲便利方法。 :) – 2011-05-12 17:02:25

+2

從技術上講,它們是工廠方法,但在ObjC世界中沒有人稱之爲那種。 – bbum 2011-05-12 17:57:30

1

首先,我建議你不要從任何方法返回一個NSMutableArray。最好使用NSArray來避免一些非常難以調試的問題。我的主張是:

您聲明可變數組並填充它:

NSMutableArray *arrayInMethod = [[[NSMutableArray alloc] init] autorelease]; 

然後返回一個autoreleased副本:

return [[arrayInMethod copy] autorelease]; 

最後,當你走在返回的數組,你做它可以再次變化(只有當你需要改變它時):

NSMutableArray *array = [[self methodThatReturnsAnArray] mutableCopy]; 

當你完成第e陣列,你釋放它:

[array release]; 
+0

好的。我在我的答案中編輯它。 – 2011-05-12 16:59:39

+0

我試過了,但它不起作用。 – 2011-05-13 08:40:01

+0

我在問題 – 2011-05-13 08:54:32