-1

Such a basic question, but i don't know the answer.What exactly the difference between:

NSString *str = @"Hello";

and

NSString *str = [[NSString alloc] initWithString:@"Hello"];

When should i use each one?

Andrey Chernukha
  • 21,488
  • 17
  • 97
  • 161

2 Answers2

4

A @"" expressions is replaced at compile time1 with an instance of NSConstantString, which is a specialized subclass of NSString with a fixed memory layout2. This also explains why NSString is the only object that can be initialized at compile time3.

A [[NSString alloc]initWithString:@""] produces a NSString instance, initializes that instance with a literal expression, and releases the instance. Therefore, the object allocation is superfluous and immediately discarded. Which is why you should always use just the literal when creating immutable strings.

1 The LLVM code that rewrites the expression is RewriteModernObjC::RewriteObjCStringLiteral in RewriteModernObjC.cpp.
2 To see the NSConstantString definition, cmd+click it in Xcode.
3 Creating compile time constants for other classes would be easy but it would require the compiler to use a specialized subclass. This would break compatibility with older Objective-C versions.

Jano
  • 62,815
  • 21
  • 164
  • 192
  • Btw, if you release the object created with `initWithString:` the release is ignored because your object pointer is already pointed to the `NSConstantString` instance, (at least in the current implementation of Clang), but the static analyzer of Xcode will still nag you to do it because implementing `initWithString:` as a literal is a feature of the compiler, not of the language. – Jano Apr 13 '13 at 15:20
2

When should i use each one?

NSString *str = [[NSString alloc] initWithString:@"Hello"]; //1st one

The above is redundant, and has same meaning as

NSString *str = @"Hello"; //2nd one

So always use shorter one. i.e 2nd one in my example.

EDIT:

Also see this What's the difference between NSString *s = @"string" and NSString *s = [[NSString alloc] initWithString:@"string"]?

Community
  • 1
  • 1
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140