Possible Duplicate:
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]; }