views:

92

answers:

1

I was looking at someone else's code and noticed they called 'release' on an NSString they didn't own (never called alloc/retain/copy anywhere and it wasn't a property).

This looked a bit strange to me and it made me wonder if any strange behaviour can occur if you call 'release' on an object that you either don't 'own' or whose ref count is already 0? The code below compiles/runs fine without warnings so I'm guessing there's no problem but I was just curious.

// Releasing an object I don't own
NSString *notMyString = [NSString stringWithString:@"Not mine."];
[notMyString release]; // Ignored?

// Releasing an object I own, twice
NSString *myString = [[NSString alloc] initWithString:@"Mine."];
[myString release]; // Ref count = 0
[myString release]; // Ref count = ?
+11  A: 

Yeah, don't do that. Your assessment is correct, as is your understanding of the ownership rules. Sending a message to an already released object has undefined behavior-- sometimes you'll get lucky because of other stuff going on and nothing will happen. Sometimes you'll crash immediately, sometimes later because you've corrupted something else.

quixoto
Yeah it's the long run behaviour I was worried about. Guess you can't always trust random blog 'tutorial' code as-is =). Thanks for the quick answer.
Nebs