iphone - 电话号码的 NSTextCheckingResult

标签 iphone objective-c validation 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;
}

这里是match的值:

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

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

提前致谢!

最佳答案

您使用的类不正确。 NSTextCheckingResult 是由 NSDataDetectorNSRegularExpression 完成的文本检查的结果。使用 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;
}

关于iphone - 电话号码的 NSTextCheckingResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11433364/

相关文章:

objective-c - CG_INLINE 是做什么的?

javascript - 客户端 JavaScript 字段验证

c# - ReactiveCommand 返回值和 View 反馈循环

iphone - 如何将 socket 设置为连接有 Action 的按钮?

iphone - NSPredicate中的单词边界(\b)导致NSFetchRequest不返回任何托管对象

objective-c - 在 Objective-C 中取消引用指针

ios - AVAudioRecorder/AVAudioSession 与 Apple Airpods

forms - 如何自动将标签添加到输入字段?

iphone - 在不访问源服务器的情况下实现 Apple 推送通知

iphone - UIWebView 更改 dataDetectorType 链接的颜色