What’s the difference between NSString *myString = @"Johnny Appleseed" versus NSString *myString = [NSString stringWithString: @"Johnny Appleseed"]?
Where’s a good case to use either one?
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.
In the first case, you are getting a pointer to a constant
NSString. As long as your program runs,myStringwill be a valid pointer. In the second, you are creating an autoreleasedNSStringobject with a constant string as a template. In that case,myStringwon’t point to a real object anymore after the current run loop ends.Edit: As many people have noted, the normal implementation of
stringWithString:just returns a pointer to the constant string, so under normal circumstances, your two examples are exactly the same. There is a bit of a subtle difference in that Objective-C allows methods of a class to be replaced using categories and allows whole classes to be replaced withclass_poseAs. In those cases, you might run into a non-default implementation ofstringWithString:, which may have different semantics than you expect it to. Just because it happens to be that the default implementation does the same thing as a simple assignment doesn’t mean that you should rely on subtle implementation-specific behaviour in your program – use the right case for the particular job you’re trying to do.