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".

Community
  • 1
  • 1
ma11hew28
  • 121,420
  • 116
  • 450
  • 651
  • `[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. –  Jun 08 '11 at 15:02
  • @WTP, no - it does nothing. See @Sven's answer – hooleyhoop Jun 08 '11 at 15:10
  • Now we have to use @"some string", otherwise we get this warning "Using 'stringWithString': with a literal is redundant" – Jun Jul 17 '13 at 10:42

3 Answers3

9

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

Sven
  • 22,475
  • 4
  • 52
  • 71
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.

JeremyP
  • 84,577
  • 15
  • 123
  • 161
  • 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. – Chuck Jun 08 '11 at 17:26
3

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

drekka
  • 20,957
  • 14
  • 79
  • 135