Is there any different between
NSString * str = @"123";
and
NSString * str = [[NSString alloc] initWithString:@"123"];
from compiler’s aspect?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Theoretically yes; in implementation detail, probably not.
In the first case, the compiler creates a constant string and assigns a pointer to it to the variable
str. You do not own the string.In the second case, the compiler creates a constant string (as before) but this time it is used by the run time as a parameter in initialising another string that you do own (because the second string was created using
alloc).That’s the end of the stuff you need to know.
However, there is a lot of optimisation that goes on. Because
NSStringsare immutable, you’ll find thatinitWithString:actually just returns the parameter. Normally, it would retain the parameter before returning it to you (because you are expecting to own it) but literal strings have a special retainCount (INT_MAXI think) to stop the run time from ever trying to deallocate them. So in practice, your second line of code produces identical results to the first.This incidentally, is why it is incorrect top say the string is autoreleased in the first case, because it isn’t. It’s just a constant string with a special retain count.
But you can and should safely ignore the implementation detail and just remember, you don’t own the string in the first case, but you do own it in the second case.