NSString对象是否需要分配和初始化? [英] Do NSString objects need to be alloc and init?
问题描述
菜鸟问题:
我目前的印象是,要创建对象时,需要alloc
和init
该对象.
但是,我看到看到几个示例代码,其中声明了NSString
对象,但是在后面没有看到alloc
或init
消息.
一个非常简单的例子:
NSString *myString = @"Hello World"; NSLog(@"%@" , myString);
有人可以解释为什么会这样吗?
声明不需要释放任何内存.
实例化对象可以.而且只有在调用 alloc 或 copy
时,才能实例化一个新对象.在您的示例中,您正在设置对编译器根据硬编码字符串创建的现有对象的引用.而且您不必管理它的内存,因为您没有实例化它.
我不知道我是否解释得足够清楚.
似乎已经有一个问题可以回答这个问题:
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?
这篇关于NSString对象是否需要分配和初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!