Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
894 views
in Technique[技术] by (71.8m points)

objective c - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...