如何在目标c中将int转换为字符串:示例代码 [英] How to convert from int to string in objective c: example code

查看:113
本文介绍了如何在目标c中将int转换为字符串:示例代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

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

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

如果你对字符串使用 == 运算符,你就是在比较字符串的地址(其中)它们是在内存中分配的,而不是字符串的值。这非常偶然有用(它表示你有完全相同的字符串对象),但99%的时间你想要比较这些值,你喜欢这样:

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:

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

这篇关于如何在目标c中将int转换为字符串:示例代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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