views:

38

answers:

1

In order to set cell.textLabel.text in the cellForRowAtIndexPath method I alloc and init a string. If I release this string after setting cell.textLabel.text, then the program will crash after doing this several times.

Why doesn't it crash the first time? Since the string was alloced and inited, doesn't it have to be released?

Here's the code:

    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];
+3  A: 

A classic misunderstanding of Memory Management.

You alloc cellText in the first line of code, but override it in the second line. So now you don't have access to the original object, and you release the autoreleased object, which leads to a crash.

The same within the if-statements, where you override the value again. In this situation, I'd use a normal, autoreleased NSString object, however you can also use an NSMutableString which you release yourself (but then you'll have to adjust to code to make use of the NSMutableString methods, such as appendFormat: instead of stringByAppendingFormat:)

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

This time you never alloc the string yourself, so you don't have to release it. When you override the variable, there is no problem since the previous value will get autoreleased.

JoostK