Свойство length объекта NSString имеет неверное значение
Я получаю доступ к адресной книге на iPhone и сохраняю номера телефонов внутри объекта NSString с именем numberValues. Первоначально эти телефонные номера были окружены множеством лишних слов, подобных цитатам, знакам плюс, скобкам, пробелам и т. Д., Поэтому у меня есть все эти настройки rangeOfString и stringByReplacingOccurencesOf, чтобы избавиться от всего лишнего кода.
После удаления всего лишнего мусора у меня остаются 10-значные номера телефонов, и это все. Поэтому, если у контакта есть 1 номер телефона, то у моего объекта numberValues должно быть свойство length, равное 10. Если у контакта есть 2 номера телефона, то у моего объекта numberValues должно быть свойство length, равное 20.
Вот что странно. Когда я NSLog numberValues.length на контакте с одним номером телефона, он печатает длину 12 на консоль. Если я делаю то же самое для контакта с двумя телефонными номерами, он выводит на консоль длину 23.
Я не понимаю, почему свойство length печатает со вздутым числом, когда я потратил время на удаление всего лишнего мусора, включая пустые места, И когда я NSLog объект numberValues, который вы можете ясно увидеть в журнале, что он содержит 10 цифры телефонных номеров и ничего более.
Вот как контакт с 1 номером телефона печатается в журнале, когда я делаю NSLog(@"%@", numberValues)
:
2014-01-19 10:36:54.912 PhotoTest1[2658:60b]
9495553119
И помните, что когда я делаю NSLog(@"%d", numberValues.length)
он распечатает 12.
Вот как контакт с двумя номерами телефонов печатается в журнале, когда я делаю NSLog(@"%@", numberValues)
:
014-01-19 10:36:54.737 PhotoTest1[2658:60b]
7142973557
7149557735
И помните, что когда я делаю NSLog(@"%d", numberValues.length)
он распечатает 23.
Есть идеи, почему свойства длины длиннее, чем должны быть?
Спасибо за помощь.
РЕДАКТИРОВАТЬ: Здесь весь мой код начинается сразу после того, как я успешно получаю доступ к адресной книге пользователя, а затем до того места, где я начинаю получать доступ к свойству length объекта numberValues:
int z = allContacts.count - 1;
for (int i = 0; i < z; i++)
{
NSArray *allContacts = (__bridge_transfer NSArray
*)ABAddressBookCopyArrayOfAllPeople(m_addressbook);
ABRecordRef contactPerson = (__bridge ABRecordRef)allContacts[i];
NSString *firstName = (__bridge_transfer NSString
*)ABRecordCopyValue(contactPerson, kABPersonFirstNameProperty);
ABMultiValueRef *phoneNumber = ABRecordCopyValue(contactPerson, kABPersonPhoneProperty);
NSMutableArray *numbers = [NSMutableArray array];
//NSLog(@"The count: %ld", ABMultiValueGetCount(phoneNumber));
NSString *number = (__bridge_transfer NSString*)ABMultiValueCopyArrayOfAllValues(phoneNumber);
[numbers addObject:number];
NSString *numberValues = [[NSString alloc]initWithFormat:@"%@", number];
NSLog(@"Here are the numbers for the contact named %@: %@", firstName, numberValues);
if([numberValues rangeOfString:@"+"].location == NSNotFound) {
NSLog(@"Phone Number does not contain a plus sign.");
} else {
numberValues = [numberValues stringByReplacingOccurrencesOfString:@"+1" withString:@""];
NSLog(@"This new number value should not have a + anymore: %@", numberValues);
}
if([numberValues rangeOfString:@" ("].location == NSNotFound) {
NSLog(@"No phone numbers contain blank space with start of parentheses");
} else {
NSLog(@"Phone number(s) do contain blank space with start of parentheses");
numberValues = [numberValues stringByReplacingOccurrencesOfString:@" (" withString:@""];
NSLog(@"The new number values should not contain a blank space with the start of parentheses: %@", numberValues);
}
if([numberValues rangeOfString:@") "].location == NSNotFound) {
NSLog(@"Phone number(s) do not contain ) and a blank space");
} else {
NSLog(@"Phone numbers do contain ) and a blank space");
numberValues = [numberValues stringByReplacingOccurrencesOfString:@") " withString:@""];
NSLog(@"These new phone number values should not have ) with a blank space after it: %@", numberValues);
}
if([numberValues rangeOfString:@"-"].location == NSNotFound) {
NSLog(@"No numbers contain a dash");
} else {
NSLog(@"Number(s) does contain a dash");
numberValues = [numberValues stringByReplacingOccurrencesOfString:@"-" withString:@""];
NSLog(@"The new number values should not have any dashes: %@", numberValues);
}
if([numberValues rangeOfString:@"("].location == NSNotFound) {
NSLog(@"Number(s) do not contain a (");
} else {
NSLog(@"Number(s) contains a (");
numberValues = [numberValues stringByReplacingOccurrencesOfString:@"(" withString:@""];
NSLog(@"The new number(s) should not have any ( in them: %@", numberValues);
}
if ([numberValues rangeOfString:@"\""].location == NSNotFound) {
NSLog(@"Number does not contain any quotations");
} else {
NSLog(@"Number(s) do contain quotations");
numberValues = [numberValues stringByReplacingOccurrencesOfString:@"\"" withString:@""];
NSLog(@"Numbers should not have any quotations: %@", numberValues);
}
if([numberValues rangeOfString:@")"].location == NSNotFound) {
NSLog(@"The final ) has been deleted");
} else {
NSLog(@"Need to delete the final )");
numberValues = [numberValues stringByReplacingOccurrencesOfString:@")" withString:@""];
NSLog(@"Final value(s) should not have a trailing ) at the end: %@", numberValues);
}
if([numberValues rangeOfString:@","].location == NSNotFound) {
NSLog(@"The final , has been deleted");
} else {
NSLog(@"Need to delete the final ,");
numberValues = [numberValues stringByReplacingOccurrencesOfString:@"," withString:@""];
NSLog(@"%@", numberValues);
NSLog(@"Final value(s) should not have a trailing , at the end: %lu", (unsigned long)numberValues.length);
}
if([numberValues rangeOfString:@" "].location == NSNotFound) {
NSLog(@"No blank spaces.");
} else {
NSLog(@"There are blank spaces that need to be deleted");
numberValues = [numberValues stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"%@", numberValues);
}
NSLog(@"RIGHT BEFORE THE NEW IF STATEMENT");
NSLog(@"%d", numberValues.length);
if(numberValues.length < 11) {
NSLog(@"RUNNING PFQUERY");
PFQuery *query = [PFQuery queryWithClassName:@"_User"];
[query whereKey:@"username" equalTo:numberValues];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
NSLog(@"Here are the objects that have been returned from Parse: %@", objects);
} else {
NSLog(@"CHARACTERS: %d", numberValues.length);
int howManyNumbers = numberValues.length / 10;
NSLog(@"%d", howManyNumbers);
}
РЕДАКТИРОВАТЬ 2 ДЛЯ КОММЕНТАРИИ VEDDERMATIC:
я только что сделал NSLog(@"###%@###", numberValues);
и вот как он печатает в журнале:
2014-01-19 11:06:00.529 PhotoTest1[2678:60b] ###
3097679973
###
1 ответ
Длина верна, есть еще символы, которые вы не удалите. NSString поддерживает более миллиона символов, и вы не можете проверить их все.
Вместо этого вы должны использовать RegEx, чтобы удалить все, что не является числом.
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"[^0-9]" options:0 error:nil];
NSString *phoneNumber = [regex stringByReplacingMatchesInString:phoneNumber options:0 range:NSMakeRange(0, phoneNumber.length) withTemplate:@""];