NSString intValue无法检索电话号码

And*_*rew 0 cocoa-touch objective-c type-conversion phone-number nsstring

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

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

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

- (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\n &i", phoneNumberInt, phoneNumberInt);

     return phoneNumberInt;
}
Run Code Online (Sandbox Code Playgroud)

然后当我调用这个方法时:

NSLog(@"%i", [self processPhoneNumber:self.phoneNumberTextField.text]);
Run Code Online (Sandbox Code Playgroud)

我明白了:2147483647. 我给这个方法的每个输入都返回:2147483647

Jos*_*ell 5

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

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

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