tags:

views:

15

answers:

1

Can an NSString be reused like this:

NSString *string = @"first value";

NSLog(string);

string = @"second value";

NSLog(string);

This works when tested, but is it proper coding?

Thanks.

A: 

Yes, your example is totally fine. What is your concern about it being 'improper'?

Edit: Strictly speaking it is probably safer to use:

NSLog(@"%@", string);

Instead of just logging the string directly. I don't think that's what you were asking, though.

Carl Norum
My concern is that it's not a NSMutableString. Does reassigning NSString with a different length string corrupt anything in memory?
Jim
@Jim, you're not modifying any strings in your code; just a pointer to a string.
Carl Norum
Then what happens to "first value"? Does it stay in memory or does it get disposed of? Should I release it?
Jim
@Jim, it stays in memory - it's a constant string, so there's nothing you can do about it. You don't need to release it since you didn't retain it.
Carl Norum
Great, thank you.
Jim