views:

257

answers:

1

I have this function within an iPhone project Objective C class.

While it's correct in terms of the desired functionality, after a few calls, it crashes into the debugger.

So I think it's a case of bad 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;

}

A: 

Every time you iterate over your for loop, you're allocating a new NSString. While these NSStrings are autoreleased, they won't actually be released until after all the processing of your last input is finished. In the meantime, you'll allocate a potentially infinite amount of memory. The solution is to create your own autorelease pool and drain it every trip through the for loop. It'll 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];
}

That'll free up the memory used by your current pointer right away.

Warren Pena