Novice Objective-C NSString Question
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 fin开发者_运维知识库e. 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 allocatedString
To summarize, you're creating an unnecessary overhead by using initWithFormat
when the string is static. The static string will be created in both ways, the second way will just copy the content into an other NSString
.
-initWithFormat:
is useful for when you need to substitute stuff in that you don't (and/or can't) know at compile time.
For example:
id value = ...; //some user-entered value, say like "42"
NSString * allocatedString = [[NSString alloc] initWithFormat:@"The user-entered value is: %@", value];
NSLog(@"%@", allocatedString); //logs "The user-entered value is: 42"
[allocatedString release];
The advent of Objective-C 2.0 has given developers the pleasure of convenient syntax that allow for freer, more dynamic declaration of variables, similar to what you would get in the scripting languages. In your case, there is no difference between the two statements under Automatic Reference Counting. There is similar shorthand syntax for declaring other Objective-C data structures as well ( e.g. NSArray *array = [@"Foo", @"Bar", @"Hello World"]; )
精彩评论