【问题标题】:NSPredicate - Evaluate with two conditionsNSPredicate - 使用两个条件进行评估
【发布时间】:2013-12-10 06:26:17
【问题描述】:

我想知道如何使用 NSPredicate 评估满足两个条件的 NSString。例如,如何检查一个至少应该有一个大写字母和一个数字的字符串。

【问题讨论】:

    标签: iphone objective-c regex nspredicate


    【解决方案1】:

    您可以对两个或多个条件使用 ANDing。

     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];
    

    您可以在 NSPredicate HERE 上查看更多信息。

    【讨论】:

    • 嗨..您的回答似乎是正确的。但我能够在几行代码中使用 reg ex 来做到这一点。谢谢你的帮助..
    【解决方案2】:

    一种方法是:

    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];
    

    另一种解决方案是复合谓词,请参阅此问题,例如如何使用复合谓词create a Compound Predicate in coreData xcode iphone

    【讨论】:

    • 嗨..您的回答似乎是正确的。但我能够在几行代码中使用 reg ex 来做到这一点。谢谢你的帮助..
    【解决方案3】:

    我自己找到了解决方案。我用正则表达式和谓词来解决这个问题。

    NSPredicate *pwdCheck = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"(?=.*?[A-Z])(?=.*?[0-9]).*"];
    bool isValid = [pwdCheck evaluateWithObject:@"99a99A3w"];
    

    感谢您的帮助

    【讨论】:

      猜你喜欢
      • 2020-07-04
      • 1970-01-01
      • 1970-01-01
      • 2015-01-27
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      • 2016-09-25
      • 1970-01-01
      相关资源
      最近更新 更多