NSTextCheckingResult用于电话号码

Chr*_*ris 11 iphone validation objective-c ios5

有人能告诉我为什么每次评估都是真的吗?!

输入是:jkhkjhkj.我输入的phone字段并不重要.它每次都是真的......

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

这是值match:

(NSTextCheckingResult *) $4 = 0x0ab3ba30 <NSPhoneNumberCheckingResult: 0xab3ba30>{0, 8}{jkhkjhkj}
Run Code Online (Sandbox Code Playgroud)

我正在使用RegEx,NSPredicate但我已经读过,因为iOS4建议使用,NSTextCheckingResult但我找不到任何好的教程或示例.

提前致谢!

Luk*_*man 37

您正在错误地使用该类.NSTextCheckingResult是由NSDataDetector或执行文本检查的结果NSRegularExpression.NSDataDetector改为使用:

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;
}
Run Code Online (Sandbox Code Playgroud)