What about when I use NSString?
Code:
NSString *myString = @"Hello!";
There is no alloc init and we have @"Hello" stored in that pointer.
The "@" sign tells the compiler to create a string literal. Under the covers, it calls code that allocates an immutable string object.
Until recently, strings were the only things you could create using literal syntax. However, Apple recently added support for other types of object literals:
Creates an NSNumber with the value 10:
Code:
@[@"string1", @"string2", @"string3"];
Creates an NSArray containing 3 strings.
Under the covers, the compiler generates code equivalent to
Code:
[NSArray arrayWithObjects: @"string1", @"string2", @"string3", nil];
----------
What about when I use NSString?
Code:
NSString *myString = @"Hello!";
There is no alloc init and we have @"Hello" stored in that pointer.
The key point is that
NSString *someString;
or
SomeType *someVar;
NEVER creates a string object. It declares a pointer that can be used to point to a string object.
That goes for any declaration. It never creates an object - it just defines a pointer variable that CAN point to an object, or to nothing at all. A zero (or nil) pointer is a pointer that doesn't point to anything.
You need some code to go on the right side of an "=" assignment statement to assign a value to a pointer variable..
There are a variety of different things you can put on the right side of an assignment that will allocate an object for you.
@"string" is a form that creates a static string object.
The NSString class method stringWithFormat will create a string object from a format string and zero or more other parameters.