Reputation: 763
I have a method for getting all the contacts from the iPhone contacts app and i want to add the phone numbers to an object after i have removed all the spaces in the phone number string. The problem is that this only works for some of the contacts. I have noticed that in the debugger the string-objects sometimes show in a blue color and sometimes in black. Anybody have a clue what is going on here?
Images:
Does not remove spaces in phone number
Removes spaces in phone number
Code:
ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
CFArrayRef sortedPeople = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByFirstName);
//RETRIEVING THE FIRST NAME AND PHONE NUMBER FROM THE ADDRESS BOOK
CFIndex number = CFArrayGetCount(sortedPeople);
NSString *firstName;
NSString *phoneNumberFromContact;
for(int i = 0; i < number; i++)
{
ABRecordRef person = CFArrayGetValueAtIndex(sortedPeople, i);
firstName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
phoneNumberFromContact = (__bridge NSString *) ABMultiValueCopyValueAtIndex(phones, 0);
if(phoneNumberFromContact != NULL)
{
Contact *contact = [[Contact alloc]init];
contact.firstName = firstName;
phoneNumberFromContact = [phoneNumberFromContact stringByReplacingOccurrencesOfString:@" " withString:@""];
contact.phoneNumber = phoneNumberFromContact;
[self.contacts addObject:contact];
}
}
Upvotes: 0
Views: 350
Reputation: 6211
There are many characters that appear as spaces in NSString
s. Removing all instances of all of them is rather difficult. The best method for your case is to keep only the characters you want (numbers). As the answer you referenced states you need to create a set of characters to keep:
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:@"0123456789"];
Then you need to remove everything but those characters. This can be done in a few different ways. The scanner in the answer you suggested is likely the fastest. But the way with the fewest lines of code (and in my mind most readable) would be something like:
number = [[number componentsSeparatedByCharactersInSet: numbers] componentsJoinedByString: @""];
It may be slow, so if you do this a million times then keep to the scanner.
Upvotes: 1