2012-09-10 97 views
1

我有一个字符串,我需要与整数值进行比较。比较NSString和整数?

我这样做,到目前为止:

NSString *rad = [NSString stringWithFormat: @"%@", combo.selectedText]; 
srchParam.radius = rad; 
if (srchparam.radius > 5) 
{ 
    //code here 
} 

我在做什么错?

+0

你的第一行是完全没有必要的 - 你要重新字符串本身,一个额外的函数调用什么。为什么不简单'searchParam.radius = combo.selectedtext;'? – 2012-09-10 12:57:55

+0

奇怪的是,在一个字符串中存储一个半径,显然它总是一个数字。将srchParam.radius的类型更改为int,并立即将其转换。 – Martol1ni

+0

你可以通过下面的'srchParam.radius = [combo.selectedText intValue]'然后比较 –

回答

3

试试这个:

if ([combo.selectedText intValue] > 5) { 
    //code here 
} 
1
srchParam.radius = [rad intValue]; 
1

是的。使用<运算符比较NSString将比较它的内存地址,而不是魔术般的内容(记住:Objective-C不是C++,没有运算符重载)。你必须字符串的数值比较使用

if (([srchparam.radius intValue]) > 5) 
{ 
    // code here 
} 

另外,请用空格其他整数 - 您的代码将是更好,更容易阅读。

1

我猜在这里radius是一个整数。因此:

NSString *rad=[NSString stringWithFormat:@"%@",combo.selectedText]; 
srchParam.radius =[rad intValue]; 
if((srchparam.radius)>5) 
{ 
//code here 
} 
+0

非常感谢你 – khadar

+0

@khadar:在你编辑它之前,我看到你在评论中写了什么。 – Nitish

+0

我看到我的同事在我的比赛中做了一些事情。如果有任何错误,我很抱歉。 – khadar

1
NSString *rad=[NSString stringWithFormat:@"%@",combo.selectedText]; 
if([rad intValue]>5) 
{ 
//code here 
} 
+0

其工作感谢 – nivritgupta

+0

谢谢@nivritgupta – Rajneesh071

0

那将是正确的!

if([[srchparam.radius] integerValue] > 5) 

这个例子在Xcode 4.5工作与iOS SDK 6.0,如果你仍然在Xcode的4.4只是改变integerValue的intValue