码迷,mamicode.com
首页 > 其他好文 > 详细

NSPredicate的在查询中的简单使用

时间:2014-11-22 18:54:32      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:nspredicate   like   predicatewithformat   正则   

上代码吧,每块代码都可以直接跑,并附有注释和运行结果

//直接使用 == 严格匹配
NSArray *arrOriginal = [NSArray arrayWithObjects:@"c1",@"c", @"cd", @"cdd", @"cd", nil];
NSString *match = @"cd";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF == %@", match];
NSArray *results = [arrOriginal filteredArrayUsingPredicate:predicate];
NSLog(@"result===%@",results);

打印结果:
result===(
cd,
cd
)

//like匹配,类似Sql中的用法
NSArray *arrOriginal = [NSArray arrayWithObjects:@"c1",@"d", @"cd", @"cdd", @"dd",@"dcd",@"cdc", nil];
NSString *match = @"c*";//以c开头
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF like %@", match];
NSArray *results = [arrOriginal filteredArrayUsingPredicate:predicate];
NSLog(@"result===%@",results);

打印结果:
result===(
c1,
cd,
cdd,
cdc
)

//忽略大小写进行匹配
NSArray *arrOriginal = [NSArray arrayWithObjects:@"Cdd",@"cDc",@"cdd",@"dcdd", nil];
NSString *match = @"cd*";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF like[c] %@", match];
NSArray *results = [arrOriginal filteredArrayUsingPredicate:predicate];
NSLog(@"result===%@",results);

打印结果:
result===(
Cdd,
cDc,
cdd
)

//利用正则表达是进行过滤
NSArray *arrOriginal = [NSArray arrayWithObjects:@"c1",@"C3",@"d2",@"c2", nil];
NSString *match = @"^c\\d?";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
NSArray *results = [arrOriginal filteredArrayUsingPredicate:predicate];
NSLog(@"result===%@",results);

打印结果:
result===(
c1,
c2
)

//利用过滤器(数组)进行过滤
NSArray *arrFilter = [NSArray arrayWithObjects:@"aa", @"bb", nil];
NSArray *arrOriginal = [NSArray arrayWithObjects:@"dds",@"bb",@"c1",@"C3",@"bb",@"aa",@"c2", nil];
NSPredicate *predicate  = [NSPredicate predicateWithFormat:@"NOT (SELF in %@)", arrFilter];//不包含符合过滤器的内容
NSArray *results = [arrOriginal filteredArrayUsingPredicate:predicate];
NSLog(@"result===%@",results);

打印结果:
result===(
dds,
c1,
C3,
c2
)


NSPredicate的在查询中的简单使用

标签:nspredicate   like   predicatewithformat   正则   

原文地址:http://blog.csdn.net/u011439689/article/details/41383909

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!