开发者

Few beginner questions regarding NSString

开发者 https://www.devze.com 2023-01-25 13:17 出处:网络
Hey, I got couple of questions regarding NSString. How does these two statements differ? NSString *str = @\"asdasd\";开发者_运维技巧

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?


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. :)

0

精彩评论

暂无评论...
验证码 换一张
取 消