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

Categories

0 votes
973 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 Reply

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...