2012-03-15 51 views
3

我遇到了導致崩潰的內存問題。我正在循環訪問字典數組,然後在循環中通過我創建的鍵數組進行循環。我使用該鍵數組中的每個鍵來獲取字典中該鍵的值。然後我通過附加值創建一個字符串。該字符串將包含大量的數據。iPhone:在循環中創建NSString時產生巨大的內存峯值

我也在使用ARC,因此我無法手動發佈。

內存尖峯發生在stringByAppendingFormat行上。

NSString *theString = [[NSString alloc] init]; 
for (NSMutableDictionary *aDict in collectionArray) 
{ 
    for (NSString *key in itemKeys) 
    { 
     NSString *valueString = [aDict valueForKey:key]; 

     // Memory spikes here 
     theString = [theString stringByAppendingFormat:@"%@,", valueString]; 
    } 
} 
+0

aDict字典和itemKeys數組中有多少個條目? – ThomasW 2012-03-15 01:03:18

+1

你正在泄漏'theString'。一遍又一遍地。 – 2012-03-15 01:03:32

+2

也許一個NSMutableString(https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableString_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableString/)會對此更合適。你可以對它使用appendString。您也可以預先預先計算所需的緩衝容量 – Ben 2012-03-15 01:05:51

回答

7

相反的NSString,你應該使用一個NSMutableString。試試這個:

NSMutableString *theString = [[NSMutableString alloc] init]; 
for (NSMutableDictionary *aDict in collectionArray) 
{ 
    for (NSString *key in itemKeys) 
    { 
     NSString *valueString = [aDict valueForKey:key]; 

     // Memory spikes here 
     [theString appendFormat:@"%@,", valueString]; 
    } 
} 

編輯: 這可能會解決你的問題,如果你的字典和itemKeys的長度不是特別大。但是,如果它們很大,則需要像循環一樣在循環中使用autoreleasepool:https://stackoverflow.com/a/7804798/211292另外,如果您所做的只是用逗號分隔值,請考慮Tommy的更改。

4

撇開其他地方回答的問題 - 你會不斷創建一個新的字符串,包括舊的加上一些額外的,讓舊的autorelease池,至少在你退出方法之前不會被排空 - 下面是:

NSArray *values = [aDict objectsForKeys:itemKeys notFoundMarker:@""]; 
theString = [values componentsJoinedByString:@","]; 

似乎做你想要的(當然,如果你在結尾處添加一個額外的逗號)沒有任何顯式的排序內循環。