What is the difference between these two lines?
NSString * string = @"My String";
NSString * string = [[[NSString alloc] initWithString:@"MyString"] autorelease]
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.
@”My String” is a literal string compiled into the binary. When loaded, it has a place in memory. The first line declares a variable that points to that point in memory.
From the string programming guide:
The second line allocates a string by taking that literal string. Note that both @”My String” literal strings are the same. To prove this:
Outputs the same memory address:
What’s telling is not only are the first two string the same memory address, but if you don’t change the code, it’s the same memory address every time you run it. It’s the same binary offset in memory. But, not only is the copy different but it’s different every time you run it since it’s allocated on the heap.
The autorelease has no affect according to the doc ref above. You can release them but they are never deallocated. So, they are equal not because both are autoreleased string but that they’re both constants and the release is ignored.