Can any one tell the difference between:
NSString* myStr = @"Some value";
and
NSString* myStr = [[NSString alloc] initWithString:@""];
why i should alloc a string even i can give some value directly..?
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.
From Apple’s String Programming Guide, “Creating Strings“
The “compiler makes such object constants unique […]” suggests to me that string literals are interned for each module. As far as I know, interning and object lifetime & memory management are the main differences between the two approaches.
As for why one might use the latter, if for some reason you wanted
myStrto not be a unique, interned string, then you might try the-initWithString:approach, though the interned string would still exist, using-copywould be simpler (as NR4TR points out) and (as Yuji notes in the comments) the resulting string will likely be the exact same one as the string literal, despite what Apple’s documentation suggests.