問題描述
我有一個電話號碼,格式為易于閱讀的電話號碼,即 (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 不能用于檢索電話號碼的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!