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