开发者

Initiating NSString outside an if() statement assigning it inside and releasing afterwards causes a crash

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开发者_C百科 this make the app crash?!  
  [cellText release];

...


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];


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜