objective-c 如何在目标 c 中从 int 转换为字符串:示例代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1104815/
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 21:53:42  来源:igfitidea点击:

How to convert from int to string in objective c: example code

objective-cnsstringint

提问by john

I am trying to convert from an int to a string but I am having trouble. I followed the execution through the debugger and the string 'myT' gets the value of 'sum' but the 'if' statement does not work correctly if the 'sum' is 10,11,12. Should I not be using a primitive int type to store the number? Also, both methods I tried (see commented-out code) fail to follow the true path of the 'if' statement. Thanks!

我正在尝试从 int 转换为字符串,但遇到了问题。我通过调试器跟踪执行,字符串 'myT' 获得了 'sum' 的值,但如果 'sum' 为 10,11,12,则 'if' 语句无法正常工作。我不应该使用原始 int 类型来存储数字吗?此外,我尝试的两种方法(请参阅注释掉的代码)都无法遵循“if”语句的真实路径。谢谢!

int x = [my1 intValue]; 
    int y = [my2 intValue]; 
    int sum = x+y;
    //myT = [NSString stringWithFormat:@"%d", sum];
    myT = [[NSNumber numberWithInt:sum] stringValue];

    if(myT==@"10" || myT==@"11" || myT==@"12")
        action = @"numGreaterThanNine";

采纳答案by grahamparks

The commented out version is the more correct way to do this.

注释掉的版本是更正确的方法。

If you use the ==operator on strings, you're comparing the strings' addresses (where they're allocated in memory) rather than the values of the strings. This is very occasional useful (it indicates you have the exact same string object), but 99% of the time you want to compare the values, which you do like so:

如果您==在字符串上使用运算符,您将比较字符串的地址(它们在内存中的分配位置)而不是字符串的值。这偶尔很有用(它表明您拥有完全相同的字符串对象),但是在 99% 的情况下您想要比较这些值,您喜欢这样做:

if([myT isEqualToString:@"10"] || [myT isEqualToString:@"11"] || [myT isEqualToString:@"12"])

回答by Scott

If you just need an int to a string as you suggest, I've found the easiest way is to do as below:

如果您只需要按照您的建议将 int 转换为字符串,我发现最简单的方法是执行以下操作:

[NSString stringWithFormat:@"%d",numberYouAreTryingToConvert]

回答by Robert

You can use literals, it's more compact.

您可以使用文字,它更紧凑。

NSString* myString = [@(17) stringValue];

(Boxes as a NSNumberand uses its stringValuemethod)

(框作为NSNumber并使用其stringValue方法)

回答by Terry Wilcox

==shouldn't be used to compare objects in your if. For NSStringuse isEqualToString:to compare them.

==不应该用于比较if. 对于NSString使用isEqualToString:对它们进行比较。

回答by Amol

int val1 = [textBox1.text integerValue];
int val2 = [textBox2.text integerValue];

int resultValue = val1 * val2;

textBox3.text = [NSString stringWithFormat: @"%d", resultValue];

回答by Ashwini Chougale

Simply convert intto NSStringuse :

只需转换intNSString使用:

  int x=10;

  NSString *strX=[NSString stringWithFormat:@"%d",x];