2012-07-11 13 views
11

Qualcuno può dirmi perché questa valutazione è sempre vera ?!NSTextCheckingResult per i numeri di telefono

L'input è: jkhkjhkj. Non importa ciò che digito nel campo phone. E 'vero ogni volta ...

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

Ecco il valore della match:

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

stavo usando RegEx e NSPredicate ma ho letto che da quando iOS4 si consiglia di utilizzare NSTextCheckingResult ma posso trovare qualche buon tutorial o esempio su questo.

Grazie in anticipo!

+0

"Consigliato" in quale scenario? Per verificare se un determinato testo è un numero di telefono, questo metodo non è in realtà utile. – darkheartfelt

+0

Elaborare - Posso passare "333-3333-3" (non un numero di telefono valido) alla risposta accettata e ci riesce. – darkheartfelt

risposta

37

Si sta utilizzando la classe in modo errato. NSTextCheckingResult è il risultato di un controllo del testo eseguito da NSDataDetector o NSRegularExpression. Utilizzare invece 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

Stavo proprio per scrivere esattamente questo! –

+0

Grazie mille! Un esempio del genere era esattamente quello che stavo cercando. – Chris

+0

Questo ha funzionato. Grande aiuto. –

Problemi correlati