Buscar..


Sintaxis

  • Subestaciones de cadena de formato de predicado
    • Especificadores de cadena de formato C:% d,% s,% f, etc.
    • Sustitución de objetos:% @
    • Sustitución de Keypath:% K
  • Operadores de comparación de predicados
    • =, ==: La expresión de la mano izquierda es igual a la expresión de la mano derecha
    • > =, =>: La expresión de la mano izquierda es mayor o igual que la expresión de la mano derecha
    • <=, = <: La expresión de la mano izquierda es menor o igual que la expresión de la mano derecha
    • >: La expresión de la mano izquierda es mayor que la expresión de la mano derecha
    • <: La expresión de la mano izquierda es menos que la expresión de la mano derecha
    • ! =, <>: La expresión de la mano izquierda no es igual a la expresión de la mano derecha
    • ENTRE: La expresión de la mano izquierda se encuentra entre o igual a cualquiera de los valores de la expresión de la derecha, que especifica los límites inferior y superior, por ejemplo: ENTRE {0, 5}
  • Operadores de compuestos predicados
    • Y, &&: Lógico Y
    • O, ||: O lógico
    • NO,!: NO lógico
  • Operadores de comparación de cadenas de predicado
    • BEGINSWITH: La expresión de la mano izquierda comienza con la expresión de la mano derecha
    • ENDSWITH: la expresión de la mano izquierda termina con la de la mano derecha
    • CONTIENE: La expresión de la mano izquierda contiene la expresión de la mano derecha.
    • LIKE: La expresión de la mano izquierda es igual a la expresión de la mano derecha, con sustitución de comodín
      • *: Coincide con cero o más caracteres
      • ?: Empareja un personaje

Creando un NSPredicate usando predicateWithBlock

C objetivo

NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id item, 
                                                               NSDictionary *bindings) {
    return [item isKindOfClass:[UILabel class]];
}];

Rápido

let predicate = NSPredicate { (item, bindings) -> Bool in
    return item.isKindOfClass(UILabel.self)
}

En este ejemplo, el predicado coincidirá con los elementos que son de la clase UILabel .

Creando un NSPredicate usando predicateWithFormat

C objetivo

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"self[SIZE] = %d", 5)];

Rápido

let predicate = NSPredicate(format: "self[SIZE] >= %d", 5)

En este ejemplo, el predicado hará coincidir los elementos que son matrices con una longitud de al menos 5.

Creando un NSPredicate con Variables de Sustitución

Un NSPredicate puede usar variables de sustitución para permitir que los valores se unan sobre la marcha.

C objetivo

NSPredicate *template = [NSPredicate predicateWithFormat: @"self BEGINSWITH $letter"];
NSDictionary *variables = @{ @"letter": @"r" };
NSPredicate *beginsWithR = [template predicateWithSubstitutionVariables: variables];

Rápido

let template = NSPredicate(format: "self BEGINSWITH $letter")
let variables = ["letter": "r"]
let beginsWithR = template.predicateWithSubstitutionVariables(variables)

El predicado de la plantilla no se modifica por predicateWithSubstitutionVariables . En su lugar, se crea una copia, y esa copia recibe las variables de sustitución.

Usando NSPredicate para filtrar una matriz

C objetivo

NSArray *heroes = @[@"tracer", @"bastion", @"reaper", @"junkrat", @"roadhog"];

NSPredicate *template = [NSPredicate predicateWithFormat:@"self BEGINSWITH $letter"];

NSDictionary *beginsWithRVariables = @{ @"letter": @"r"};
NSPredicate *beginsWithR = [template predicateWithSubstitutionVariables: beginsWithRVariables];

NSArray *beginsWithRHeroes = [heroes filteredArrayUsingPredicate: beginsWithR];
// ["reaper", "roadhog"]

NSDictionary *beginsWithTVariables = @{ @"letter": @"t"};
NSPredicate *beginsWithT = [template predicateWithSubstitutionVarables: beginsWithTVariables];

NSArray *beginsWithTHeroes = [heroes filteredArrayUsingPredicate: beginsWithT];
// ["tracer"]

Rápido

let heroes = ["tracer", "bastion", "reaper", "junkrat", "roadhog"]

let template = NSPredicate(format: "self BEGINSWITH $letter")

let beginsWithRVariables = ["letter": "r"]
let beginsWithR = template.predicateWithSubstitutionVariables(beginsWithRVariables)

let beginsWithRHeroes = heroes.filter { beginsWithR.evaluateWithObject($0) }
// ["reaper", "roadhog"]

let beginsWithTVariables = ["letter": "t"]
let beginsWithT = template.predicateWithSubstitutionVariables(beginsWithTVariables)

let beginsWithTHeroes = heroes.filter { beginsWithT.evaluateWithObject($0) }
// ["tracer"]

Validación de formularios utilizando NSPredicate

NSString *emailRegex = @"[A-Z0-9a-z]([A-Z0-9a-z._-]{0,64})+[A-Z0-9a-z]+@[A-Z0-9a-z]+([A-Za-z0-9.-]{0,64})+([A-Z0-9a-z])+\\.[A-Za-z]{2,4}";    NSString *firstNameRegex = @"[0-9A-Za-z\"'-]{2,32}$";
NSString *firstNameRegex = @"[ 0-9A-Za-z]{2,32}$";
NSString *lastNameRegex = @"[0-9A-Za-z\"'-]{2,32}$";
NSString *mobileNumberRegEx = @"^[0-9]{10}$";
NSString *zipcodeRegEx = @"^[0-9]{5}$";
NSString *SSNRegEx = @"^\\d{3}-?\\d{2}-?\\d{4}$";
NSString *addressRegEx = @"^[ A-Za-z0-9]{2,32}$";
NSString *cityRegEx = @"^[ A-Za-z0-9]{2,25}$";
NSString *PINRegEx = @"^[0-9]{4}$";
NSString *driversLiscRegEx = @"^[0-9a-zA-Z]{5,20}$";

-(BOOL)validateEmail {
    //Email address field should give an error when the email address begins with ".","-","_" .
    NSPredicate *emailPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];   
    return ([emailPredicate evaluateWithObject:self.text] && self.text.length <= 64 && ([self.text rangeOfString:@".."].location == NSNotFound));
}

- (BOOL)validateFirstName {
    NSPredicate *firstNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", firstNameRegex];
    return [firstNamePredicate evaluateWithObject:self.text];
}

- (BOOL)validateLastName {
    NSPredicate *lastNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", lastNameRegex];
    return [lastNamePredicate evaluateWithObject:self.text];
}

- (BOOL)validateAlphaNumericMin2Max32 {
    NSPredicate *firstNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", firstNameRegex];
    return [firstNamePredicate evaluateWithObject:self.text];
}

- (BOOL)validateMobileNumber {
    NSString *strippedMobileNumber =  [[[[self.text stringByReplacingOccurrencesOfString:@"(" withString:@""]
                                        stringByReplacingOccurrencesOfString:@")" withString:@""]
                                        stringByReplacingOccurrencesOfString:@"-" withString:@""]
                                        stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    NSPredicate *mobileNumberPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", mobileNumberRegEx];
    
    return [mobileNumberPredicate evaluateWithObject:strippedMobileNumber];
}

- (BOOL)validateZipcode {
    NSPredicate *zipcodePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", zipcodeRegEx];
    
    return [zipcodePredicate evaluateWithObject:self.text];
}

- (BOOL)validateSSN {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", SSNRegEx];

return [predicate evaluateWithObject:self.text];
}

- (BOOL)validateAddress {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", addressRegEx];
    
    return [predicate evaluateWithObject:self.text];
}

- (BOOL)validateCity {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", cityRegEx];
    return [predicate evaluateWithObject:self.text];
}

- (BOOL)validatePIN {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", PINRegEx];    
    return [predicate evaluateWithObject:self.text];
}
   - (BOOL)validateDriversLiscNumber {
    if([self.text length] > 20) {
        return NO;
    }
    NSPredicate *driversLiscPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", driversLiscRegEx];
    
    return [driversLiscPredicate evaluateWithObject:self.text];
}

NSPredica con la condición `AND`,` OR` y `NOT`

El predicado condicional será más limpio y seguro al usar la clase NSCompoundPredicate que proporciona operadores booleanos básicos para los predicados dados.

C objetivo

Y - Condición

  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"samplePredicate"];
  NSPredicate *anotherPredicate = [NSPredicate predicateWithFormat:@"anotherPredicate"];
  NSPredicate *combinedPredicate = [NSCompoundPredicate andPredicateWithSubpredicates: @[predicate,anotherPredicate]];

O - Condición

 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"samplePredicate"];
 NSPredicate *anotherPredicate = [NSPredicate predicateWithFormat:@"anotherPredicate"];
 NSPredicate *combinedPredicate = [NSCompoundPredicate orPredicateWithSubpredicates: @[predicate,anotherPredicate]];

NO - Condición

 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"samplePredicate"];
 NSPredicate *anotherPredicate = [NSPredicate predicateWithFormat:@"anotherPredicate"];
 NSPredicate *combinedPredicate = [NSCompoundPredicate notPredicateWithSubpredicate: @[predicate,anotherPredicate]];


Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow