views:

927

answers:

2

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?

+8  A: 

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:

http://stackoverflow.com/questions/329977/cocoa-memory-management-with-nsstring

Sergio Acosta
Thank you Sergio...I now understand.
ChrisR
+3  A: 

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.

Don McCaughey