NSString分配和初始化 [英] NSString allocation and initializing
问题描述
之间的区别:
NSString *string1 = @"This is string 1.";
和
NSString *string2 = [[NSString alloc]initWithString:@"This is string 2.];
为什么我不分配和初始化第一个字符串,但它仍然工作?我想我应该分配NSString,因为它是一个对象?
Why am I not allocating and initializing the first string, yet it still works? I thought I was supposed to allocate NSString since it is an object?
触摸,
-(IBAction) clicked: (id)sender{
NSString *titleOfButton = [sender titleForState:UIControlStateNormal];
NSString *newLabelText = [[NSString alloc]initWithFormat:@"%@", titleOfButton];
labelsText.text=newLabelText;
[newLabelText release];
}
为什么不为titleOfButton字符串分配和初始化?我调用的方法是为我做的?
Why do I not allocate and initialize for the titleOfButton string? Does the method I call do that for me?
此外,我使用XCode 4,但我不喜欢iOS 5,所以我不使用ARC,如果这是重要的请不要说我
Also, I'm using XCode 4, but I dislike iOS 5, and such, so I do not use ARC if that matters. Please don't say I should, I am just here to find out why this is so. Thanks!
推荐答案
变量 string1
是 NSString
字符串文字。编译器在可执行文件中为其分配空间。它被加载到内存中,并在程序运行时初始化。它只要应用程序运行就存在。您不需要保留
或发布
。
The variable string1
is an NSString
string literal. The compiler allocates space for it in your executable file. It is loaded into memory and initialized when your program is run. It lives as long as the app runs. You don't need to retain
or release
it.
变量 string2
的生命周期只要你指定,直到你 release
它的最后一个引用。
The lifespan of variable string2
is as long as you dictate, up to the point when you release
its last reference. You allocate space for it, so you're responsible for cleaning up after it.
变量的生命周期 titleOfButton
您可以为其分配空间,是方法的生命 -clicked:
。这是因为方法 -titleForState:
返回 autorelease
-d NSString
。
The lifespan of variable titleOfButton
is the life of the method -clicked:
. That's because the method -titleForState:
returns an autorelease
-d NSString
. That string will be released automatically, once you leave the scope of the method.
您不需要创建 newLabelText
。这一步是多余的和凌乱。只需将 labelsText.text
属性设置为 titleOfButton
:
You don't need to create newLabelText
. That step is redundant and messy. Simply set the labelsText.text
property to titleOfButton
:
labelsText.text = titleOfButton;
为什么要使用属性?因为设置保留
属性会将 titleOfButton
的引用计数增加一(这就是为什么它被称为 retain
属性),因此 titleOfButton
指向的字符串将在 -clicked
Why use properties? Because setting this retain
property will increase the reference count of titleOfButton
by one (that's why it's called a retain
property), and so the string that is pointed to by titleOfButton
will live past the end of -clicked:
.
在此示例中,考虑使用 retain
的另一种方法是 labelsText.text
是由 titleOfButton
指向的字符串的拥有权。只要 labelsText
生命(除非一些其他变量也拥有该字符串的所有权),该字符串将持续。
Another way to think about the use of retain
in this example is that labelsText.text
is "taking ownership" of the string pointed to by titleOfButton
. That string will now last as long as labelsText
lives (unless some other variable also takes ownership of the string).
这篇关于NSString分配和初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!