Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do NSString objects need to be alloc and init?

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?

like image 760
ChrisR Avatar asked Mar 12 '09 01:03

ChrisR


2 Answers

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?

like image 70
Sergio Acosta Avatar answered Oct 25 '22 13:10

Sergio Acosta


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.

like image 44
Don McCaughey Avatar answered Oct 25 '22 11:10

Don McCaughey