Я обращаюсь к адресной книге на iPhone и сохраняю номера телефонов внутри объекта NSString с именем numberValues. Первоначально эти телефонные номера окружены тонны лишних нежелательных котировок, плюс знаки, круглые скобки, пробелы и т. Д., Поэтому у меня есть все эти методы rangeOfString и stringByReplacingOccurencesOf, чтобы избавиться от всего лишнего кода.свойство length объекта NSString имеет неправильное значение
После удаления всего лишнего мусора я остаюсь с 10-значными номерами телефонов, и это все. Поэтому, если у контакта есть 1 номер телефона, тогда мой объект numberValues должен иметь свойство длины 10. Если контакт имеет 2 номера телефона, то мой объект numberValues должен иметь свойство длины 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.
Вот как связаться с 2 телефонными номерами отпечатков в журнал, когда я NSLog(@"%@", numberValues)
:
014-01-19 10:36:54.737 PhotoTest1[2658:60b]
7142973557
7149557735
И помните, что когда я делаю NSLog(@"%d", numberValues.length)
распечатать 23.
Любые идеи, почему свойства длины длиннее, чем они должны быть?
Спасибо за помощь.
EDIT: Вот весь мой код, начиная сразу после того, как я успешно получить доступ к адресной книге пользователя, а затем весь путь вниз, где я начинаю доступ к длине свойство 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);
}
EDIT 2 дЛЯ КОММЕНТАРИЕВ VEDDERMATIC'S:
Я просто сделал NSLog(@"###%@###", numberValues);
и это, как он печатает в журнале:
2014-01-19 11:06:00.529 PhotoTest1[2678:60b] ###
3097679973
###
Похоже, у вас есть префикс '\ n', потому что номер появляется на следующей строке из журнала. – dasblinkenlight
Показать код, который вы хотите для очистки телефонных номеров. – rmaddy
Как проверка работоспособности, сделайте что-то вроде «NSLog (@« ##% @ ## », numberValues)» и посмотрите, есть ли ведущие или завершающие символы.Например, ваш журнал строк не будет отображать два конечных пробела. – veddermatic