Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate - Evaluate with two conditions

I want to know how to evaluate NSString which satisfied two conditions using NSPredicate. For example how to check a string that should have atleast one upper case letter and atleast one number.

like image 332
nath Avatar asked Feb 25 '26 10:02

nath


2 Answers

You can use ANDing for two or more condition.

 NSManagedObjectContext *context = [appDelegate managedObjectContext];
 NSEntityDescription *entityDescription = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
 NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entityDescription];

 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"fbUID = %@ AND birthDate = %d AND birthMonth = %d AND greetingYear = %d", uID, birthDate, birthMonth, greetingYear];

//NSLog(@"%@ :",predicate);
[fetchRequest setPredicate:predicate];

 NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];

You can check more on NSPredicate HERE.

like image 169
Gyanendra Singh Avatar answered Feb 27 '26 02:02

Gyanendra Singh


One way to do this is:

NSCharacterSet *upperCaseCharacters = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLKMNOPQRSTUVWXYZ"];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];

NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {

    return ([evaluatedObject rangeOfCharacterFromSet:upperCaseCharacters].location != NSNotFound && [evaluatedObject rangeOfCharacterFromSet:numbers].location != NSNotFound);

}];

NSString *stringToEvaluate = @"aasad5D";

BOOL result = [predicate evaluateWithObject:stringToEvaluate];

Another solution is compound predicate, see this question for example how to use compound predicates create a Compound Predicate in coreData xcode iphone.

like image 41
selma.suvalija Avatar answered Feb 27 '26 00:02

selma.suvalija



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!