NSString intValue 不能用于检索电话号码

NSString intValue not working for retrieving phone number(NSString intValue 不能用于检索电话号码)
本文介绍了NSString intValue 不能用于检索电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个电话号码,格式为易于阅读的电话号码,即 (123) 123-4567

I have a phone number formatted as an easy to read phone number, i.e., (123) 123-4567

但是,当我想在代码中使用该电话号码时,我需要将该字符串解析为一个数字变量(例如 int)

However, when I want to use that phone number in code, I need to parse that string into a number variable (such as an int)

但是,[string intValue]; 不起作用 - 我在以前的项目中使用了大约一百万次 intValue,全部没问题,但是在这里,我传入的每个字符串,我都会得到相同的随机 int 退出:

However, [string intValue]; doesn't work - I've used intValue about a million times in previous projects, all with no problem, however here, every string I pass in, I get the same, random int back out:

- (int)processPhoneNumber:(NSString *)phoneNumber {
      NSMutableString *strippedString = [NSMutableString stringWithCapacity:10];

      for (int i=0; i<[phoneNumber length]; i++) {
           if (isdigit([phoneNumber characterAtIndex:i])) {
                  [strippedString appendFormat:@"%c",[phoneNumber characterAtIndex:i]];
           }
      }

     NSLog(@"clean string-- %@", strippedString);

     int phoneNumberInt = [strippedString intValue];

     NSLog(@"**** %d
 &i", phoneNumberInt, phoneNumberInt);

     return phoneNumberInt;
}

那么当我调用这个方法时:

Then when I call this method:

NSLog(@"%i", [self processPhoneNumber:self.phoneNumberTextField.text]);

我得到:2147483647.我给这个方法的每个输入都会返回:2147483647

I get: 2147483647. Every input I give this method returns: 2147483647

推荐答案

正如 CRD 已经解释的那样,您正在尝试将该字符串转换为太小而无法容纳该值的类型,并且您正在取回最大值该类型的可能值.

As CRD has already explained, you're trying to convert that string to a type that's too small to hold the value, and you're getting back the maximum possible value for that type.

然而,你真正的问题是更深层次的.电话号码"并不是真正的号码.它不代表数量.你永远不会对一个进行算术运算.它实际上是一串数字,你应该这样处理它.不要转换它;只对字符串进行操作.

Your real problem is deeper, however. A phone "number" isn't really a number. It doesn't represent a quantity. You would never perform arithmetic on one. It's actually a string of digits, and you should handle it that way. Don't convert it; just operate on the string.

另请参阅表示电话号码的正确方法是什么?

这篇关于NSString intValue 不能用于检索电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Comparing in objective C - Implicit conversion of #39;int#39; to #39;id#39; is disallowed with ARC(在目标 C 中进行比较 - ARC 不允许将“int隐式转换为“id)
how can i pass an int value through a selector method?(如何通过选择器方法传递 int 值?)
Check if object is Class type(检查对象是否为类类型)
UIScrollView scroll not working after pushed with a navigation controller(使用导航控制器推送后 UIScrollView 滚动不起作用)
UIWebView content not adjusted to new frame after rotation(旋转后 UIWebView 内容未调整为新框架)
iPhone: adding button to scrollview makes button inaccessible to interaction(iPhone:向滚动视图添加按钮使按钮无法交互)