Leakazoid
Leakazoid

Reputation: 1

Spotted a leak in UITextView delegate method. Confused about solution

I've got a problem with an UITextView and one of its delegate methods in my navigation based app:

- (BOOL)textView:aView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

I managed to limit the max length of text the user can input using the above method. But I'm using a leaky array for that matter I think.

The problem is: I want to save the amount of typed characters right in the very moment the user enters the last line of my textview. I then use that value to calculate the string length - which I compare to the textview's content size to set a limit. The code works fine - but since the method it's inside of is updating with every text input, I'm having trouble releasing the array in the right moment.

Here's some code:

if (numLines == 9)
{
    if (!numCharsArray) 
    {
        numCharsArray = [[NSMutableArray alloc] initWithCapacity:1]; // Stack trace gives this line 3,3% of the leak.
    }

    numChars = tView.text.length;
    NSNumber *number = [[NSNumber alloc] initWithInteger:numChars]; // This line gets 77,3%.
    [numCharsArray addObject:number]; // This line gets the rest, 24,3%.
    [number release];

    startChars = [[numCharsArray objectAtIndex:0] integerValue];

    NSString *lastLine = [[NSString alloc]initWithString:[[tView text] substringFromIndex:startChars]];
    CGSize lineSize = [lastLine sizeWithFont:tView.font forWidth:tView.contentSize.width lineBreakMode:UILineBreakModeWordWrap];
    [lastLine release];

    if (range.length > text.length) 
    {
        return YES;
    }
    else if (numLines == 9 && lineSize.width >= tView.contentSize.width - 45)
    {
        return NO;
    }
}
else
{
    numCharsArray = nil;
    /* 
    if(numCharsArray)
    {
        [numCharsArray release];
    }
    */
}

I tried the out-commented statement above, but that gives me an app crash once I leave the last line of the textview. And as you can see in the code comments - without releasing the array I get a leak.

So how and where do I release that array correctly - keeping it safe while the user is on the last line?

Upvotes: 0

Views: 259

Answers (1)

Praveen-K
Praveen-K

Reputation: 3401

Just replace with

first one

numCharsArray = [NSMutableArray array]; // you do not need to release 
                                           //explicitly as its autorelease numberWithInt

second one

NSNumber *number = [NSNumber numberWithInt:numChars]; //autorelease

NSString *lastLine = [[tView text] substringFromIndex:startChars];

Upvotes: 1

Related Questions