2012-09-10 99 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