0

我正在做一个基于 ARC 的项目。我正在从一个大文本文件中获取文本,需要从中删除空格或换行符。以下代码在模拟器上运行良好,但在 iPad 上崩溃并且无法完全运行(这可能是内存问题)。例如,如果循环需要运行 2000 次,它会在 iPad 上运行 1800 次后崩溃。

- (BOOL)formatTheText {
NSString *content = [NSString stringWithContentsOfURL:_textFileURL
                     encoding:NSUTF8StringEncoding 
                            error:NULL];

NSRange paraRange = {0,1};
NSString *modifiedContent = @"";
BOOL previousLineWasEmpty = NO;
int lineNumber = 0;

while (paraRange.location < [content length]) {

    NSRange currentParaRange = [content paragraphRangeForRange:paraRange];
    NSString *paragraph = [content substringWithRange:currentParaRange];
    NSCharacterSet *newLineSet = [NSCharacterSet newlineCharacterSet];

    NSArray *array = [paragraph componentsSeparatedByCharactersInSet:newLineSet];
    NSString *currentParagraph = @"";

    for (NSString *line in array) {
        currentParagraph = [currentParagraph stringByAppendingString:line];
    }

    // Add a space when combining two lines
    modifiedContent = [modifiedContent stringByAppendingFormat:@"%@ ",currentParagraph];
    paraRange.location += currentParaRange.length;

    if ([currentParagraph length] == 0) {

        // If previous line was empty just add a new line character
        if (previousLineWasEmpty) {
            modifiedContent = [modifiedContent stringByAppendingString:@"\n"];

        } else {
            // Add two lines for the start of a new paragraph
            modifiedContent = [modifiedContent stringByAppendingString:@"\n\n"];
        }
        previousLineWasEmpty = YES;

    } else {
        previousLineWasEmpty = NO;
    }
    lineNumber++;
}
self.cleanedString = modifiedContent;
return YES;
}
4

0 回答 0