NSString不必在cellForRowAtIndexPath:方法中发布?

时间:2010-10-10 12:41:46

标签: objective-c cocoa-touch uitableview nsstring memory-management

为了在cellForRowAtIndexPath方法中设置cell.textLabel.text,我分配并初始化一个字符串。如果我在设置cell.textLabel.text之后释放了这个字符串,那么在执行了几次后程序会崩溃。

第一次为什么不崩溃?由于字符串是分配和引入的,所以不必释放它吗?

以下是代码:

    NSString *cellText = [[NSString alloc] init];
    cellText = [NSString stringWithFormat:@"(%.1f points", totalpoints];
    if (showNumberOfPlayers) {
        cellText = [cellText stringByAppendingFormat:@", %i players) ", [[playerArray objectAtIndex:indexPath.row] count]];
    }
    else {
        cellText = [cellText stringByAppendingString:@") "];
    }

    cell.textLabel.text = [cellText stringByAppendingString:teamList];
    [cellText release];

1 个答案:

答案 0 :(得分:4)

对内存管理的经典误解。

您在第一行代码中alloc cellText,但在第二行中覆盖它。因此,现在您无权访问原始对象,并释放自动释放的对象,从而导致崩溃。

if语句中的相同内容,您再次覆盖该值。在这种情况下,我会使用一个普通的,自动释放的NSString对象,但你也可以使用你自己发布的NSMutableString(但是你必须调整代码才能使用NSMutableString方法,例如appendFormat:而不是stringByAppendingFormat:

NSString *cellText = [NSString stringWithFormat:@"(%.1f points", totalpoints];

这次你自己永远不会alloc字符串,所以你不必释放它。当您覆盖变量时,没有问题,因为之前的值将被自动释放。