问题描述
每当我需要创建一个新的NSString变量时,我总是对其进行分配和初始化.似乎有时候您不想这样做.您如何知道何时分配和初始化NSString,何时不分配?
Whenever I need to create a new NSString variable I always alloc and init it. It seems that there are times when you don't want to do this. How do you know when to alloc and init an NSString and when not to?
推荐答案
不,那没有道理.
变量从程序遇到声明它的那一刻起就存在:
The variable exists from the moment the program encounters the point where you declare it:
NSString *myString;
此变量不是NSString.它存储指向NSString的指针.这就是*
所指示的:该变量包含一个指针.
This variable is not an NSString. It is storage for a pointer to an NSString. That's what the *
indicates: That this variable holds a pointer.
NSString 对象仅在创建对象之时存在:
The NSString object exists only from the moment you create one:
[[NSString alloc] init];
指向该对象的指针仅在您将变量分配给它的那一刻起出现在该变量中:
and the pointer to that object is only in the variable from the moment you assign it there:
myString = [[NSString alloc] init];
//Or, initializing the variable in its declaration:
NSString *myString = [[NSString alloc] init];
因此,如果您要从其他地方获取一个字符串对象(例如,substringWithRange:
),则可以跳过创建一个新的空对象的步骤,因为您只需要替换指向空字符串的指针即可.指向另一个指针.
Thus, if you're going to get a string object from somewhere else (e.g., substringWithRange:
), you can skip creating a new, empty one, because you're just going to replace the pointer to the empty string with the pointer to the other one.
有时您确实想创建一个空字符串;例如,如果您一次要获取一串字符串(例如,从NSScanner中获取),并且想要将其中的一些或全部连接成一个大字符串,则可以创建一个空的可变字符串(使用和init
)并将其发送给appendString:
消息以进行串联.
Sometimes you do want to create an empty string; for example, if you're going to obtain a bunch of strings one at a time (e.g., from an NSScanner) and want to concatenate some or all of them into one big string, you can create an empty mutable string (using alloc
and init
) and send it appendString:
messages to do the concatenations.
您还需要release
由alloc
创建的任何对象.这是《内存管理编程指南》 中的规则之一.
You also need to release
any object you create by alloc
. This is one of the rules in the Memory Management Programming Guide.
这篇关于什么时候不分配和初始化NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!