2012-07-11 44 views
11

有人可以告訴我爲什麼這每次評估真實?!輸入:jkhkjhkj。我在phone字段中輸入的內容無關緊要。這是每一個真正的時間...NSTextCheckingResult的電話號碼

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} 

我用正則表達式和NSPredicate但我讀過,因爲它的iOS4推薦使用NSTextCheckingResult,但我可以在這方面找不到任何好的教程或例子。

在此先感謝!

+0

「推薦」在什麼情況下?爲了檢查某個文本是否是電話號碼,此方法實際上沒有幫助。 – darkheartfelt 2015-01-08 00:39:54

+0

詳細說明 - 我可以將「333-3333-3」(不是有效的電話號碼長度)傳遞給接受的答案併成功。 – darkheartfelt 2015-01-08 00:40:26

回答

37

您正在使用該類錯誤。 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; 
} 
+0

我正要寫下這個! – 2012-07-11 13:30:44

+0

非常感謝!這樣的例子正是我所期待的。 – Chris 2012-07-11 13:50:01

+0

這工作。很好的幫助。 – 2014-07-28 06:15:01