在COCOA中的NSPredicate表示的就是一种判断。一种条件的构建。我们可以先通过NSPredicate中的predicateWithFormat方法来生成一个NSPredicate对象表示一个条件,然后在别的对象中通过evaluateWithObject方法来进行判断,返回一个布尔值。
废话不多说,直接上代码:
- (BOOL)validatePhoneNumber { // 手机号以13, 15,18开头,八个 \d 数字字符 NSString *phoneNumberRegEx = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$"; NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneNumberRegEx]; BOOL isCorrect = [regExPredicate evaluateWithObject:[self lowercaseString]]; return isCorrect ? YES : NO; }
上面这段代码是判断手机号码是否正确。建立一个phoneNumberRegEx的字符串,根据predicateWithFormat:建立一个NSPredicate对象表示一个条件,再用valuateWithObject判断是否匹配.其中的lowercaseString是返回一个小写的字符串(具体见我字符串常用用法的博客)。
字符串中使用了很多iOS中的正则表达式(见我博客iOS常用正则表达式)。
iOS常用判断代码示例:
- (BOOL)validateUserName { NSString *RegEx = @"^[\\d\\w_]{5,20}$"; NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", RegEx]; BOOL isCorrect = [regExPredicate evaluateWithObject:[self lowercaseString]]; return isCorrect ? YES : NO; } - (BOOL)validateUserNameNoChar { NSString *phoneNumberRegEx = @"^[\\d_]{5,20}$"; NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneNumberRegEx]; BOOL isCorrect = [regExPredicate evaluateWithObject:[self lowercaseString]]; return isCorrect ? YES : NO; } - (BOOL)validatePhoneNumber { // 手机号以13, 15,18开头,八个 \d 数字字符 NSString *phoneNumberRegEx = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$"; NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneNumberRegEx]; BOOL isCorrect = [regExPredicate evaluateWithObject:[self lowercaseString]]; return isCorrect ? YES : NO; } - (BOOL)validateEmail { NSString *mailRegEx = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", mailRegEx]; BOOL isCorrect = [regExPredicate evaluateWithObject:[self lowercaseString]]; return isCorrect ? YES : NO; } - (BOOL)validateBlank { NSString *priceRegEx =@"\\s*"; NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", priceRegEx]; BOOL isCorrect = [regExPredicate evaluateWithObject:[self lowercaseString]]; return isCorrect ? YES : NO; } - (BOOL)validatePrice { NSString *priceRegEx =@"\\d*|\\d*\\.|\\d*\\.\\d{1,2}"; NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", priceRegEx]; BOOL isCorrect = [regExPredicate evaluateWithObject:[self lowercaseString]]; return isCorrect ? YES : NO; }
cocoa中的NSPredicate介绍,布布扣,bubuko.com
原文:http://www.cnblogs.com/ioslps/p/3856227.html