1

I think the question is clear enough but still - what's the difference between:

NSString *string = @"Hello world!";

and

NSString *string = [[NSString alloc] initWithString:@"Hello world!"];

Let me know if this already answers it.

Community
  • 1
  • 1
daLizard
  • 430
  • 4
  • 14
  • The reference to another post is not the same because this question is about constant strings. – zaph Jan 27 '12 at 13:45

2 Answers2

11
NSString *string = [[NSString alloc] initWithString:@"Hello world!"];

Per cocoa as cocoa naming convention, You create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy”. That means you own the string above, hence you're responsible to release the object.

NSString *string = @"Hello World";

The line above is a string literal / constant, you don't alloc it or release it. You don't own this object.

X Slash
  • 4,133
  • 4
  • 27
  • 35
  • 4
    Actually in this case there is really no difference due to compiler "smarts". String constants have a very large reference count (MAXINT) and the compiler will treat the second example the same as the first. – zaph Jan 27 '12 at 13:44
  • Interesting to know, do you actually know where can I read more about this? Cheers. – X Slash Jan 27 '12 at 13:49
  • So, if I don't own the string literal, does that mean it will exist throughout the entire app execution? – daLizard Jan 27 '12 at 13:58
  • 1
    Yes, literal string is compiled into the binary and persists for the life of the executing app. – X Slash Jan 27 '12 at 14:10
  • 1
    @Zaph: Not exactly. The compiler does, for each code example, exactly what it says; the first example will indeed create a string object and try to init it with the literal string. The string object may respond to `initWithString:` by releasing itself and returning the string. (This is likely *not* to happen with NSMutableString.) So the result is as you said: the former code ultimately assigns the literal string to the variable. But the mechanism is not: the creation of a new extra string object still happens, but it's thrown away before the assignment. – Peter Hosey Dec 18 '12 at 05:51
1

NSString *string = [[NSString alloc] initWithString:@"Hello World!"];

This code creates a strong reference and the variable will be retained. It then assigns the value "Hello World!" to it.

NSString *string = @"Hello World!";

This code simply assigns the value "Hello World!" to the NSString object. It's not creating any references of any kind. If your object isn't already initialized and retained, the object will be destroyed at the end of the running scope.

Simon Germain
  • 6,834
  • 1
  • 27
  • 42