是否有必要在将一个字符串与另一个变量进行比较之前将其分配给一个变量? [英] Is it necessary to assign a string to a variable before comparing it to another?

查看:17
本文介绍了是否有必要在将一个字符串与另一个变量进行比较之前将其分配给一个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 NSString 的值与字符串Wrong"进行比较.这是我的代码:

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

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

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

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

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

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

推荐答案

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

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

不,为什么不这样做:

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

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

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

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

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

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

Yes, you can do something like:

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

这篇关于是否有必要在将一个字符串与另一个变量进行比较之前将其分配给一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆