Obj-C: [NSString stringWithString:@"string"] vs. @"string"
Asked Answered
R

3

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

Roomer answered 8/6, 2011 at 14:56 Comment(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.Drinkwater
@WTP, no - it does nothing. See @Sven's answerBeanfeast
Now we have to use @"some string", otherwise we get this warning "Using 'stringWithString': with a literal is redundant"Unsustainable
L
9

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

Logos answered 8/6, 2011 at 15:9 Comment(0)
B
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.

Bernadette answered 8/6, 2011 at 15:12 Comment(1)
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.Thoughtless
R
3

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

Reams answered 4/11, 2011 at 0:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.