Convert NSMutableString without memory leak?

I have this function in an Objective C class for iPhone.

While this is true in terms of the desired functionality, after a few calls it crashes into the debugger.

So, I think this is a case of poor memory management, but I'm not sure where.

- (NSString *)stripHtml:(NSString *)originalText {
// remove all html tags (<.*>) from the originalText string
NSMutableString *strippedText = [[NSMutableString alloc] init];

BOOL appendFlag = YES;
for( int i=0; i<[originalText length]; i++ ) {
    NSString *current = [originalText substringWithRange:NSMakeRange(i, 1)];
    if( [current isEqualTo:@"<"] )
        appendFlag = NO;
    if( appendFlag ) 
        [strippedText appendString:current];
    if( [current isEqualTo:@">"] )
        appendFlag = YES;
}

NSString *newText = [NSString stringWithString:strippedText];
[strippedText release];
return newText;

      

}

0


a source to share


1 answer


Each time you iterate over the for loop, you are assigning a new NSString. Although these NSStrings are auto-implemented, they will not actually be released until after processing the last input is complete. In the meantime, you will allocate a potentially infinite amount of memory. The solution is to create your own autoresource pool and drain it every ride through a for loop. It will look something like this:

BOOL appendFlag = YES;
for( int i=0; i<[originalText length]; i++ ) {    
NSAutoreleasePool *pool = [NSAutoreleasePool new];
// rest of for loop body
[pool drain];
}

      



This will free the memory used by your current pointer.

0


a source







All Articles