简体   繁体   English

Objective-C语法混乱

[英]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: 注意:

  • If this is an instance variable it actually will be initialized automatically — to nil . 如果这是一个实例变量,则实际上它会自动初始化为nil
  • If you use the variable somewhere in your code without initializing it in every possible branch ( 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;是在一行上声明多个指针变量的正确方法。)

NSString *string; NSString *字符串;

The first your just declaring that there will be a variable that is an NSString , named string , but not initializing it. 首先,您只需声明将存在一个名为stringNSString变量,但不会对其进行初始化。

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";
}

NSString *string = [NSString string]; NSString * string = [NSString字符串];

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM