可能重複:
Most memory efficient way to split an NSString in to substrings試圖分裂一個非常大的字符串
我試圖分裂一個20MB的字符串。我試過使用componentsSeparatedByString,但它消耗太多的RAM。我認爲這是由於它拆分了字符串,但也使原始字符串保持不變。這意味着該字符串會有效地存儲在內存中兩次(即使我在拆分之後立即釋放原始字符串仍然是個問題)。
我對Objective C非常陌生。我嘗試寫一些代碼將字符串添加到找到的字符串數組中時將字符串從原始字符串中移除。這個想法是,當發現字符串的可變數組變大時,原始字符串變小。唯一的問題是它泄漏內存和崩潰。如果有人能告訴我我做錯了什麼,那麼你會很棒!
NSRange range = [mainHtml rangeOfString:@"<p class=NumberedParagraph>"];
int counter = 1;
// locations will == int max if it can't find any more occurances
while (range.location < [mainHtml length]) {
NSString *curStr;
NSRange curStrRange;
NSRange rangeToSearchIn = NSMakeRange(range.location+1, [mainHtml length] - range.location - 1);
NSRange nextRange = [mainHtml rangeOfString:@"<p class=NumberedParagraph>" options:NSCaseInsensitiveSearch range:rangeToSearchIn];
if (nextRange.location > [mainHtml length])
{
// This is the last string - get everything up to the end of the file
curStrRange = NSMakeRange(0, [mainHtml length]);
curStr = [mainHtml substringFromIndex:range.location];
} else {
curStrRange = NSMakeRange(range.location, nextRange.location - range.location);
curStr = [mainHtml substringWithRange:curStrRange];
}
// Remove the substring just processed from the orignal string
// * it crashes here, normally on the 3rd itteration
mainHtml = [mainHtml substringFromIndex:curStrRange.location + curStrRange.length];
range = [mainHtml rangeOfString:@"<p class=NumberedParagraph>"];
[self.parts addObject:curStr];
}
'if(nextRange.location> [mainHtml length])'我不認爲這是正確的,不應該是'> ='? – jv42
我對Objective C沒有把握,但是我知道在其他語言(C#)中,索引是基於0的,而長度不是這樣,所以最後一個字符會很長 - 1.我會發現。 – JoeS