Samuli Lehtonen
Samuli Lehtonen

Reputation: 3860

Few beginner questions regarding NSString

Hey, I got couple of questions regarding NSString.

How does these two statements differ?

NSString *str = @"asdasd";
NSString *str = [[NSString alloc] initWithString:@"asdasd"];

Am I correct that the other is a static string which isn't released from memory until program is closed? I have always used the 2nd method and released it when I don't need it anymore. Could some explain a bit more?

Upvotes: 0

Views: 116

Answers (1)

Dave DeLong
Dave DeLong

Reputation: 243156

Theoretically, they are different. The first string is constants and cannot be released. The second one (again, theoretically) is allocated on the heap and should be released when you're done with it. (This is according to the memory management rules)

However, in this particular instance there is no difference, because the initializer will just return the original string. because the compiler is smart enough to see that "aha, you're allocating an immutable object from an constant string, so the resulting string is guaranteed to be identical to the original constant string, so I can just skip the whole allocation thing and just re-use the constant string".

So it turns out that they're going to be the same string. However, your initial gut reactions are correct, and you should keep following them. :)

Upvotes: 4

Related Questions