NSString *notAllocatedString = @"This string was not allocated.";
NSString *allocatedString = [[NSString alloc] initWithFormat:@"This string was allocated."];
NSLog(@"%@", notAllocatedString);
NSLog(@"%@", allocatedString);
Both of these strings print perfectly fine. What exactly is the difference between the two? I mean, I understand that a section of memory is allocated for the second one and should be released but other than that – what are the advantages and disadvantages of each of these?
The first one is static and the compiler and the runtime is in charge of the memory. You should use this method when you can. The compiler has some nice memory optimisation (like all string that are equal will point to the same adress in memory).
The second one, you created it a run time, and you’re in charge of the memory. This is the method you should use when the string is dynamic. It will copy the content of the static string into the
allocatedStringTo summarize, you’re creating an unnecessary overhead by using
initWithFormatwhen the string is static. The static string will be created in both ways, the second way will just copy the content into an otherNSString.