views:

41

answers:

2

Sticking to the rule of releasing everything I'm creating, why does the line [cellText release] crash my app? It must be something really simple, I'm quite new to iPhone apps dev.

...

  NSMutableString *cellText = [[NSMutableString alloc] initWithString:@""];

  // the cell is a section cell
  if (/* some condition */) {    
    cellText = @"some text";
  }

  // why does this make the app crash?!  
  [cellText release];

...
+1  A: 

The problem is that you are actually trying to release another object, not the one that you created.

On the line cellText = @"some text"; you are assigning your pointer to another object.

You could try instead something like this

NSMutableString *cellText = nil; // make sure that the pointer is initialized with nil

// the cell is a section cell
if (/* some condition */) {    
    cellText = [[NSString alloc] initWithString:@"some text"];
}

// now you can release it (if it's nil, no problem, because sending a message to nil has no effect) 
[cellText release];
Florin
A: 

cellText is a pointer to an object. When you assign to it, you assign the pointer rather than assigning inside the object. So by doing

cellText = @"some text";

you are forgetting your original pointer and recording instead a pointer to the constant string @"some text". When you then try to release it you cause an error, because it is not an object you allocated, it is a constant. (Although I think you ought to be able to send release to a constant string, it just should do nothing, so if this crashes that is possibly a bit odd.)

Meanwhile, your original string never gets released because you no longer have a pointer to it to which to send the message.

walkytalky
Ah, ok, thanks for the explanation! That helped a lot!
ChrisB
Another question though would be: What is the correct way of assigning a text to a variable inside an if() statement? I can't put the init (as in initWithString:) inside the if as it would give me a warning that it wasn't declared?
ChrisB