@interface TFCityAddressModel : NSObject
@property (nonatomic, copy) NSString *cityName;
@property (nonatomic, copy) NSString *cityPinYin;
@property (nonatomic, copy) NSString *cityPinYinHead;
@end
@implementation TFCityAddressModel
@end
//单个字符串的查询语句
// [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@",searchBarText];
- (void)testNSPredicate
{
NSString *searchBarText = @"北京";
NSArray *_cityAddressArray = @[@"杭州",@"台北",@"北京"];
NSPredicate *_tfPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@",searchBarText];
NSArray *array = [_cityAddressArray filteredArrayUsingPredicate:_tfPredicate];
for (NSString *cityName in array)
{
CHDebugLog(@"testNSPredicate----%@",cityName);
}
}
结果如下:
CommonDemo[4098:101861] testModelNSPredicate——北京
//model查询语句
- (void)testModelNSPredicate
{
//NSString *searchBarText = @"北京";
NSString *searchBarText = @"t";
NSMutableArray *_cityAddressArray = [[NSMutableArray alloc]init];
TFCityAddressModel *_info = [[TFCityAddressModel alloc]init];
_info.cityName = @"北京";
_info.cityPinYin = @"beijing";
_info.cityPinYinHead = @"b";
[_cityAddressArray addObject:_info];
TFCityAddressModel *_info1 = [[TFCityAddressModel alloc]init];
_info1.cityName = @"台北";
_info1.cityPinYin = @"taibei";
_info1.cityPinYinHead = @"t";
[_cityAddressArray addObject:_info1];
TFCityAddressModel *_info2 = [[TFCityAddressModel alloc]init];
_info2.cityName = @"杭州";
_info2.cityPinYin = @"hangzhou";
_info2.cityPinYinHead = @"h";
[_cityAddressArray addObject:_info2];
NSPredicate *_tfPredicate = [NSPredicate predicateWithFormat:@"(cityName CONTAINS[cd] %@) OR (cityPinYin CONTAINS[cd] %@) OR (cityPinYinHead CONTAINS[cd] %@)", searchBarText, searchBarText, searchBarText];
NSArray *array = [_cityAddressArray filteredArrayUsingPredicate:_tfPredicate];
for (TFCityAddressModel *_modelInfo in array)
{
CHDebugLog(@"testNSPredicate----%@",_modelInfo.cityName);
}
}
结果如下:
CommonDemo[4098:101861] testModelNSPredicate——北京
CommonDemo[4098:101861] testModelNSPredicate----台北
- (void)testNSPredicateExpression
{
NSString *regex = @"[A-Za-z]";
//判断a是否属于正则表达式[A-Za-z],若是则正确,否则错误。
BOOL a = [self isValidateRegularExpression:@"a" byExpression:regex];
if (a)
{
CHDebugLog(@"------test testNSPredicateExpression");
}
}
//是否是有效的正则表达式
- (BOOL)isValidateRegularExpression:(NSString *)strDestination byExpression:(NSString *)strExpression
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", strExpression];
return [predicate evaluateWithObject:strDestination];
}