How do i update an existing NSString variable with a new formatted string?
for example i have a variable like this:
String1 = [NSString new];
I want this string object to be updated from time to time with new formatted contents using the standard printf format.
I can initialise a new NSString using the initWithFormat: message but this is unavailable to already instantiated objects.
Any ideas? I’m thinking i can destroy the NSString each time and re-initialise a new one but is this the correct solution each time i need to update it?
Two options:
Create a new string every time with
[[NSString alloc] initWithFormat:@"whatever"]and assign it to the variable. (Make sure you follow the memory management rules, which includes making sure the string’s previous value is released. Of course, you’ll need to follow those rules no matter how you tackle this problem.)Create an NSMutableString and update the string with the mutating methods (
appendFormat:,setString:,deleteCharactersInRange:, etc.). In this case, you’re not just updating the variable, but the string itself.Personally, I would use method 1, creating a new NSString every time. That way I don’t have to fiddle with mutation and can just create a string with the precise value I want.