在UITextView委托方法中发现了一个漏洞.对解决方案感到困惑



我有一个问题与UITextView和它的一个委托方法在我的基于导航的应用程序:

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

我设法限制了用户可以使用上述方法输入的文本的最大长度。但是我认为我正在使用一个泄漏的数组。

问题是:我想保存输入字符的数量在用户进入我的textview的最后一行的那一刻。然后,我使用该值来计算字符串长度-我比较textview的内容大小设置一个限制。代码工作得很好-但因为它里面的方法是更新与每个文本输入,我有麻烦在正确的时刻释放数组。

下面是一些代码:

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];
    }
    */
}

我尝试了上面的注释语句,但这给了我一个应用程序崩溃一旦我离开textview的最后一行。正如您在代码注释中看到的那样,如果不释放数组,就会出现泄漏。

那么我如何以及在哪里正确地释放这个数组——当用户在最后一行时保持它的安全?

第一个

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

第二个

NSNumber *number = [NSNumber numberWithInt:numChars]; //autorelease
NSString *lastLine = [[tView text] substringFromIndex:startChars];

相关内容

最新更新