我的代码有什么问题吗?

时间:2010-08-24 23:13:24

标签: objective-c

-(void)processGlyph:(int)glyphOne withGlyph:(int)glyphTwo
{
    answer = glyphOne + glyphTwo;
    NSString *tempText = [[NSString alloc] init];
    tempText = [NSString stringWithFormat:@"%i",answer];
    [self dispatchText:tempText];
    [tempText release];
}

-(void)checkReadyToProcess
{
    if (count >= 2) {
        [self processGlyph:firstGlyph withGlyph:secondGlyph];
    }
}

-(void)dispatchText:(NSString *) theText
{
    answerText.text = theText;
}

1 个答案:

答案 0 :(得分:7)

是。它在这里:

NSString *tempText = [[NSString alloc] init];//leaked
tempText = [NSString stringWithFormat:@"%i",answer];//creates new autoreleased object
...
[tempText release]; //causes an eventual crash

您正在分配NSString,将该变量替换为自动释放的NSString,然后释放自动释放的NSString。这将导致内存泄漏(来自原始NSString)和过度释放导致的崩溃。

相反,只需:

NSString *tempText = [NSString stringWithFormat:@"%i",answer];

您不必释放它。