Basically, the question is – are the following essentially the same?
NSString *value1 = ...;
NSString *value2 = [[NSString alloc] initWithString:value1];
and
NSString *value1 = ...;
NSString *value2 = [value1 copy];
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.
Conceptually, yes. However, there is one difference:
allocalways creates a new string, whereascopymay return the same string.In particular, immutable objects, such as immutable strings, are likely respond to
copyby returning themselves rather than creating and returning a copy. (After all, if you can’t change anything about the original, why would you really need a copy?) Mutable strings will respond to it by creating and returning a copy, as you’d expect.initWithString:is in the middle: It may release the receiver and return the string you gave it, similar to howcopymay return the receiver. However, if that happens, it means you wasted the creation of the string you created withalloc. Withcopy, you may not need to create any additional objects at all.About the only reason to use
allocandinitWithString:is if you have your own subclass of NSString and want to make an instance of it from an existing string.copywon’t use your desired subclass. Since subclassing NSString is practically never warranted in Cocoa, the same is true of usinginitWithString:(orstringWithString:).So the bottom line is, just use
copy(ormutableCopy). It’s shorter, clearer about your intent, and can be faster.