2012-07-11 16 views
11

¿Puede alguien decirme por qué esto se evalúa cada vez que es cierto?NSTextCheckingResult para los números de teléfono

La entrada es: jkhkjhkj. No importa lo que escriba en el campo phone. Es cada vez es cierto ...

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

Aquí es el valor de match:

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

que estaba usando expresiones regulares y NSPredicate pero he leído que ya iOS4 se recomienda utilizar NSTextCheckingResult pero no puedo No hay buenos tutoriales o ejemplos sobre esto.

¡Gracias de antemano!

+0

"Recomendado" en que escenario? Para verificar si un determinado texto es un número de teléfono, este método no es realmente útil. – darkheartfelt

+0

Para más detalles: puedo pasar "333-3333-3" (no una longitud de número de teléfono válida) a la respuesta aceptada y tiene éxito. – darkheartfelt

Respuesta

37

Está utilizando la clase incorrectamente. NSTextCheckingResult es el resultado de una verificación de texto que se realiza por NSDataDetector o NSRegularExpression. Use NSDataDetector en su lugar:

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

¡Estaba a punto de escribir exactamente eso! –

+0

¡Muchas gracias! Tal ejemplo fue exactamente lo que estaba buscando. – Chris

+0

Esto funcionó. Gran ayuda. –

Cuestiones relacionadas