【发布时间】:2012-10-11 15:56:12
【问题描述】:
我有一个电话号码,格式为易于阅读的电话号码,即(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;
}
那么当我调用这个方法时:
NSLog(@"%i", [self processPhoneNumber:self.phoneNumberTextField.text]);
我得到:2147483647。 我给这个方法的每个输入都会返回:2147483647
【问题讨论】:
-
我建议您完全走错了路。电话“号码”并不是真正的号码。它不代表数量。你永远不会对一个进行算术运算。它实际上是一串数字,你应该这样处理它。见What's the right way to represent phone numbers?
-
我 100% 支持 @Josh Caswell。在您的 int 表示中,您甚至无法判断是否需要在开头调用一些“0”!
-
您是否使用 Xcode 调试工具逐步检查代码以找出问题所在?知道代码的哪一部分不能正常工作会很有帮助。
-
这是有道理的,我同意。我将其设为 int 以便我可以轻松调用它,但您的解释更有意义。如果你把它变成答案,我会接受它
标签: objective-c cocoa-touch nsstring type-conversion phone-number