2

Would using

NSString* Test=[NSString stringWithString:@"Words"];

have any advantages over

NSString* Test=@"Words";

or is it just redundant?

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • No. An NSString is immutable, so making a copy serves no purpose (other than to chew up time/space). Likewise, the ever-popular `[NSString stringWithFormat:@"%@", someString]` is a waste of time, assuming that `someString` is an (immutable) NSString. And one I saw earlier today, `[NSString stringWithFormat:someString]`, is downright dangerous, since `someString` may contain `%` characters. – Hot Licks Jan 13 '14 at 16:45

2 Answers2

2

It's redundant. NSString objects are immutable (cannot be changed) so there is no advantage that I can see over using the literal directly.

If you did the following, however:

NSMutableString *test = [NSMutableString stringWithString:@"Words"];

Then that's a different story.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
1

Any modern ObjC compiler will warn you if you try to instantiate a string like this...

Using 'stringWithString:' with a literal is redundant

Use @"literals" unless you actually need to "operate" on the input, á la...

NSString * w = [NSString stringWithUTF8String:"Words"];

or

NSString * join = [NSString stringWithFormat:@"con%@enate", @"cat"]
Alex Gray
  • 16,007
  • 9
  • 96
  • 118