> I have a piece of code where I am stumped and was wondering what the best method would be. So I have a textfield called phone that I want to pass. However when the field is displayed it looks like (503) 555-1212. How can I format the NSString so that it only passes the numbers in the following IBAction and ignoes any nonnumber character?
> - (IBAction)openPhone:(id)sender;
> NSURL *url = [NSURL URLWithString:phone.text];
> [[UIApplication sharedApplication] openURL:url];
> }
Something that's quite handy here is NSCharacterSet for specifying types of characters. Unfortunately the closest method that NSString has for what you need is stringByTrimmingCharactersInSet:, which could be used with something like [NSCharacterSet decimalDigitCharacterSet] to strip out the numbers -- which is the opposite of what you want.
But combining that with [NSCharacterSet characterSetWithCharactersInString] could get you there in two moves:
NSString *unwantedCharacters = [phone.text stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
NSString *finalPhoneNumber = [phone.text stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString: unwantedCharacters]];
--
Justin R. Miller
http://codesorcery.net
-Bill
----------------
William Frowine, PMP
Northwest Mobile Development LLC
in...@nwmobiledev.com
Has anyone used these methods or are they pretty obscure?
- Michael
On 2/13/2012 12:26 PM, Northwest Mobile Development LLC wrote:
> Thanks Justine& Janine! Looks like what I am looking for.
janine
- (IBAction)openPhone:(id)sender {
NSString *originalPhoneNumber = phone.text;
NSCharacterSet *numbers = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
NSString *trimmedPhoneNumber = [originalPhoneNumber stringByTrimmingCharactersInSet:numbers];
NSURL *url = [NSURL URLWithString:trimmedPhoneNumber];
[[UIApplication sharedApplication] openURL:url];
}
----------------
William Frowine, PMP
Northwest Mobile Development LLC
in...@nwmobiledev.com
JM