objective-c 是否有必要在将一个字符串与另一个变量进行比较之前将其分配给一个变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1302985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 22:06:21  来源:igfitidea点击:

Is it necessary to assign a string to a variable before comparing it to another?

objective-ccocoa-touchvariables

提问by Bryan

I want to compare the value of an NSStringto the string "Wrong". Here is my code:

我想将 an 的值NSString与字符串“Wrong”进行比较。这是我的代码:

NSString *wrongTxt = [[NSString alloc] initWithFormat:@"Wrong"];
if( [statusString isEqualToString:wrongTxt] ){
     doSomething;
}

Do I really have to create an NSString for "Wrong"?

我真的必须为“错误”创建一个 NSString 吗?

Also, can I compare the value of a UILabel's textto a string without assigning the label value to a string?

另外,可我一个的值进行比较UILabeltext一个字符串没有标签值分配给字符串?

回答by Alex Rozanski

Do I really have to create an NSString for "Wrong"?

我真的必须为“错误”创建一个 NSString 吗?

No, why not just do:

不,为什么不这样做:

if([statusString isEqualToString:@"Wrong"]){
    //doSomething;
}

Using @""simply creates a string literal, which is a valid NSString.

使用@""简单地创建一个字符串文字,它是一个有效的NSString.

Also, can I compare the value of a UILabel.text to a string without assigning the label value to a string?

另外,我可以将 UILabel.text 的值与字符串进行比较而不将标签值分配给字符串吗?

Yes, you can do something like:

是的,您可以执行以下操作:

UILabel *label = ...;
if([someString isEqualToString:label.text]) {
    // Do stuff here 
}

回答by Wevah

if ([statusString isEqualToString:@"Wrong"]) {
    // do something
}

回答by h4xxr

Brian, also worth throwing in here - the others are of course correct that you don't need to declare a string variable. However, next time you want to declare a string you don't need to do the following:

Brian,这里也值得一提——其他的当然是正确的,你不需要声明一个字符串变量。但是,下次您要声明字符串时,您无需执行以下操作:

NSString *myString = [[NSString alloc] initWithFormat:@"SomeText"];

Although the above does work, it provides a retained NSString variable which you will then need to explicitly release after you've finished using it.

尽管上述方法确实有效,但它提供了一个保留的 NSString 变量,在您使用完它之后,您将需要显式释放该变量。

Next time you want a string variable you can use the "@" symbol in a much more convenient way:

下次你想要一个字符串变量时,你可以以更方便的方式使用“@”符号:

NSString *myString = @"SomeText";

This will be autoreleased when you've finished with it so you'll avoid memory leaks too...

这将在您完成后自动释放,因此您也将避免内存泄漏......

Hope that helps!

希望有帮助!

回答by h4xxr

You can also use the NSString class methods which will also create an autoreleased instance and have more options like string formatting:

您还可以使用 NSString 类方法,它也将创建一个自动发布的实例并有更多的选项,如字符串格式:

NSString *myString = [NSString stringWithString:@"abc"];
NSString *myString = [NSString stringWithFormat:@"abc %d efg", 42];