0

我有一个将距离作为 NSString 返回的项目。我想检查该距离是否小于或等于或大于 10,000 英尺。我遇到了一个错误,上面写着“ARC不允许将'int'隐式转换为'NSString *'。” 有谁知道如何将 NSString 转换为 Integer?或者如何构造代码?谢谢!

- (IBAction)btnPress:(id)sender {

NSString *distanceInFeet = [[NSUserDefaults standardUserDefaults]
                           stringForKey:@"distanceInFeet"];

if ([distanceInFeet intValue] <= 10000)
{

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Close" message:@"Distance is close" delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil, nil];
    [alert show];
    return;

else
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Far" message:@"Distance is far" delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil, nil];
    [alert show];
    return;
}

} 
4

2 回答 2

1

你为什么不简单地试试这个?

 

if ([distanceInFeet intValue]<=10000)
{

或者

if ([distanceInFeet integerValue]<=10000)
{

编辑:

根据您对代码的编辑,并显示正确的错误...

NSString *distanceInFeet = [NSString alloc] initWithFormat:@"%ld", [[NSUserDefaults standardUserDefaults]
                           stringForKey:@"distanceInFeet"]];
于 2012-12-16T11:38:26.797 回答
1

使用NSNumberFormatter,如果字符串不是有效数字,它将返回 nil。

NSString *distanceInFeet ...
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *distanceInFeetNumber = [numberFormatter numberFromString:ditanceInFeet];

if ([distanceInFeetNumber intValue] <= 10000) {
    //do stuff in here
}
于 2012-12-16T11:40:58.203 回答