Chris Chris - 1 month ago 18
Objective-C Question

NSTextCheckingResult for phone numbers

Can someone tell me why this evaluates every time to true?!

The input is:

jkhkjhkj
. It doesn't matter what I type into the
phone
field. It's every time true...

NSRange range = NSMakeRange (0, [phone length]);
NSTextCheckingResult *match = [NSTextCheckingResult phoneNumberCheckingResultWithRange:range phoneNumber:phone];
if ([match resultType] == NSTextCheckingTypePhoneNumber)
{
return YES;
}
else
{
return NO;
}


Here is the value of
match
:

(NSTextCheckingResult *) $4 = 0x0ab3ba30 <NSPhoneNumberCheckingResult: 0xab3ba30>{0, 8}{jkhkjhkj}


I was using RegEx and
NSPredicate
but I've read that since iOS4 it's recommended to use
NSTextCheckingResult
but I can't find any good tutorials or examples on this.

Thanks in advance!

Answer

You are using the class incorrectly. NSTextCheckingResult is the result of a text checking that is done by NSDataDetector or NSRegularExpression. Use NSDataDetector instead:

NSError *error = NULL;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber error:&error];

NSRange inputRange = NSMakeRange(0, [phone length]);
NSArray *matches = [detector matchesInString:phone options:0 range:inputRange];

// no match at all
if ([matches count] == 0) {
    return NO;
}

// found match but we need to check if it matched the whole string
NSTextCheckingResult *result = (NSTextCheckingResult *)[matches objectAtIndex:0];

if ([result resultType] == NSTextCheckingTypePhoneNumber && result.range.location == inputRange.location && result.range.length == inputRange.length) {
    // it matched the whole string
    return YES;
}
else {
    // it only matched partial string
    return NO;
}
Comments