this is a beginner question.
I needed a new string variable today, so I did something like this:
NSString* newString = nil;
if(something)
newString = @"a value";
else
newString = @"different value";
and it worked just fine. Still, I do know a little about memory allocation, and I feared this might cause problems somehow, so I changed in the end the code to:
NSString* newString = [NSString stringWithFormat:@""];
if(something) ...
Is it a bad practice what I previously did?
I know some variables get allocated automatically, so you don’t need to call alloc for them, but wouldn’t initializing them as nil work just as well?
I’m sorry if this question sounds silly, I came to objective-c from php and my knowledge about memory management is close to.. nil
[edit]
This is not a question about nil vs @””;
My question is if it’s ok to simply use a NSString = something (nil, @””, @”a value”) and if, in general, it’s ok to do this for objects.
For example, instead of doing a NSRandomObject = [[NSRandomObject* alloc] init]; I can simply do NSRandomObject = aValue;
Since both branches of the
ifassign a value tonewString, assignment prior toifhas no effect.Deciding on whether or not to initialize a string to
nilvs. an empty string is an application-level decision, often centered around the distinction between “the string is not there” and “the string is there, but it is empty”.