NSTextCheckingResult用于电话号码 [英] NSTextCheckingResult for phone numbers

查看:157
本文介绍了NSTextCheckingResult用于电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我为什么每次评估为真??

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

输入为: jkhkjhkj 。我在电话字段中键入的内容无关紧要。每次都是真的......

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;
}

这是匹配

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

我使用的是RegEx和 NSPredicate 但是我我读过,因为iOS4建议使用 NSTextCheckingResult ,但我找不到任何好的教程或示例。

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.

提前致谢!

推荐答案

您正在错误地使用该课程。 NSTextCheckingResult 是文本检查的结果,由 NSDataDetector NSRegularExpression 。改为使用 NSDataDetector

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;
}

这篇关于NSTextCheckingResult用于电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆