[英]Objective-c syntax confusion
Could anyone tell me the difference between 谁能告诉我之间的区别
NSString* string;
And 和
NSString* string = [NSString string];
Just like in C, 就像在C中一样
NSString *string;
declares the variable (pointer) string
but gives it no value. 声明变量(指针)
string
但不提供任何值。 This means you can't use the variable until you've initialized it, for example by doing string = @"foo";
这意味着您必须先初始化变量才能使用它,例如通过执行
string = @"foo";
. 。
Note: 注意:
nil
. nil
。 if
conditions, etc.) then the compiler will complain. if
有条件等),则编译器将抱怨。 To avoid this you could just set it to an empty string or nil
to start with. nil
开头。 The line 线
NSString *string = [NSString string];
uses the +string
method of the NSString
class to create an empty string. 使用
NSString
类的+string
方法创建一个空字符串。 You could also use @""
. 您也可以使用
@""
。
(Further note: I recommend using NSString *string
instead of NSString* string
because the former hides a syntax idiosyncrasy: NSString *string1, *string2;
is the correct way to declare multiple pointer variables on one line.) (还要注意:我建议使用
NSString *string
而不是NSString* string
因为前者隐藏了语法特质: NSString *string1, *string2;
是在一行上声明多个指针变量的正确方法。)
The first your just declaring that there will be a variable that is an NSString
, named string
, but not initializing it. 首先,您只需声明将存在一个名为
string
的NSString
变量,但不会对其进行初始化。
You might do this when you want a string to contain one of a range of values, determined by some condition: 如果您希望字符串包含一个值范围(由某些条件决定)中的一个,则可以执行以下操作:
NSString *string;
if (condition) {
string = @"This condition";
} else {
string = @"That condition";
}
The second you are doing all of the above, with the additional step of initializing your string
variable to an empty string. 第二步,您完成了上述所有操作,另外还有将
string
变量初始化为空字符串的附加步骤。
You might do this when you want a string to contain a specific single value: 当您希望字符串包含特定的单个值时,可以这样做:
NSString *string = @"There are no conditions"
NSString *string;
Creates a pointer but not a string object (instance). 创建一个指针,但不创建字符串对象(实例)。 It may be initialized to nil or not depending on where it is an compiler options.
根据它在哪里是编译器选项,它可能被初始化为nil或不初始化为nil。 In other words it creates a place (memory storage) for a pointer to an
NSString
bot no NSString
object. 换句话说,它为指向
NSString
bot no NSString
对象的指针创建了一个位置(内存存储)。
NSString *string = [NSString string];
Creates an empty string object (instance) and a pointer to it. 创建一个空字符串对象(实例)和一个指向它的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.