17

I've seen people do something like [NSString stringWithString:@"some string"]. Why not just do @"some string"?

For an example, look at the facebook-ios-sdk.

+[NSString stringWithString:] -- what's the point? is a similar question, but none of the answers address [NSString stringWithString:@"some string"] vs. @"some string".

3
  • [NSString stringWithString:@"some string"] copies @"some string" from read-only memory, which is baked in the executable, but as NSString is immutable anyways, I don't see the point either. Commented Jun 8, 2011 at 15:02
  • @WTP, no - it does nothing. See @Sven's answer Commented Jun 8, 2011 at 15:10
  • Now we have to use @"some string", otherwise we get this warning "Using 'stringWithString': with a literal is redundant" Commented Jul 17, 2013 at 10:42

3 Answers 3

9

Actually there is no difference. [NSString stringWithString: str] just does nothing and returns str if str is immutable already.

Sign up to request clarification or add additional context in comments.

Comments

7

There's no difference other than the extra key strokes needed. In fact, with a constant string as a parameter (or an immutable string) you just get another pointer to the parameter.

The main use of the method is in subclasses:

[NSMutableString stringWithString: @"fdghdfjl"];

will give you a mutable autoreleased copy of the original.

1 Comment

It's also used as an alternative to [[someString copy] autorelease] — that is, it guarantees that you have an non-owned immutable string — that some people find more readable, I think.
3

One thing to note about stringWithString: is that it will throw an exception if the source string is nil.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.