Подтвердить что ты не робот

NSTextCheckingResult для телефонных номеров

Может кто-нибудь сказать мне, почему это каждый раз оценивает true?!

Вход: jkhkjhkj. Неважно, что я ввожу в поле phone. Это каждый раз правда...

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

Вот значение match:

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

Я использовал RegEx и NSPredicate, но я читал, что с iOS4 рекомендуется использовать NSTextCheckingResult, но я не могу найти никаких хороших учебных пособий или примеров.

Спасибо заранее!

4b9b3361

Ответ 1

Вы неправильно используете класс. 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;
}