NSString对象是否需要分配和初始化? [英] Do NSString objects need to be alloc and init?

查看:70
本文介绍了NSString对象是否需要分配和初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

菜鸟问题:

我目前的印象是,要创建对象时,需要allocinit该对象.

但是,我看到看到几个示例代码,其中声明了NSString对象,但是在后面没有看到allocinit消息.

一个非常简单的例子:

NSString *myString = @"Hello World";

NSLog(@"%@" , myString);

有人可以解释为什么会这样吗?

解决方案

声明不需要释放任何内存.

实例化对象可以.而且只有在调用 alloc copy

时,才能实例化一个新对象.

在您的示例中,您正在设置对编译器根据硬编码字符串创建的现有对象的引用.而且您不必管理它的内存,因为您没有实例化它.

我不知道我是否解释得足够清楚.

似乎已经有一个问题可以回答这个问题:

原义的NSString是自动释放的还是需要释放的?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆