Noob question:
I'm currently under the impression that when you want to create an object, you need to alloc
and init
that object.
However, I've seen seen several sample codes where an NSString
object is declared, yet I see no alloc
or init
messages following...
A very simple example:
NSString *myString = @"Hello World"; NSLog(@"%@" , myString);
Can someone explain why this is so?
Declaring a variable does not require releasing any memory.
Instantiating objects does. And you only instantiate a new object if you call alloc or copy
In your example, you are setting your reference to the already existing object that the compiler creates from the hard-coded string. And you don't have to manage its memory because you didn't instantiate it.
I don't know if I'm explaining it clearly enough.
EDIT:
It looks like there is already a question that answers this:
Is a literal NSString autoreleased or does it need to be released?
When you embed an NSString
literal in your code, such as @"hello, world'
, the compiler allocates space for it in your executable file and it's loaded into memory and initialized when your program starts.
Since it's part of your executable, it lives for the whole lifespan of your app. There's no need to retain or release it. The NSString *myString
variable you create for it is a pointer to the place in memory where the compiler put the NSString
literal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With