OC中的謂詞操作是針對(duì)于數(shù)組類型的,他就好比數(shù)據(jù)庫(kù)中的查詢操作,數(shù)據(jù)源就是數(shù)組,這樣的好處是我們不需要編寫很多代碼就可以去操作數(shù)組,同時(shí)也起到過(guò)濾的作用,我們可以編寫簡(jiǎn)單的謂詞語(yǔ)句,就可以從數(shù)組中過(guò)濾出我們想要的數(shù)據(jù)。非常方便。
下面直接上代碼操作一下.
Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, retain) NSString *name;
@property (nonatomic, assign) NSInteger age;
+ (instancetype)personWithName:(NSString *)name andAge:(NSInteger)age;
@end
創(chuàng)建一個(gè)Person類,里面有_name和_age兩個(gè)屬性.
Person.m
#import "Person.h"
@implementation Person
+ (instancetype)personWithName:(NSString *)name andAge:(NSInteger)age {
Person *person = [[Person alloc]init];
person.name = name;
person.age = age;
return person;
}
@end
main.h
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSArray *persons = [NSArray arrayWithObjects:
[Person personWithName:@"zhangsan" andAge:20],
[Person personWithName:@"lisi" andAge:25],
[Person personWithName:@"wangwu" andAge:22],
[Person personWithName:@"zhaoliu" andAge:30],
[Person personWithName:@"duqi" andAge:33],
[Person personWithName:@"zhengba" andAge:50],
[Person personWithName:@"liujiu" andAge:28],
[Person personWithName:@"zhangshi" andAge:79],
nil];
創(chuàng)建一個(gè)數(shù)組,元素是Person *對(duì)象.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age<%d", 30];
NSArray *filterArray = [persons filteredArrayUsingPredicate:predicate];
創(chuàng)建一個(gè)謂詞,也就是一個(gè)篩選條件,即年齡在30以下的,并且創(chuàng)建一個(gè)新的數(shù)組fileArray來(lái)接受符合條件的元素.
predicate = [NSPredicate predicateWithFormat:@"age < %d && name = %@", 30, @"zhangsan"];
filterArray = [persons filteredArrayUsingPredicate:predicate];
for (Person *p in filterArray) {
NSLog(@"pName : %@", p.name);
}
當(dāng)然也可以創(chuàng)建多個(gè)篩選條件的謂詞
predicate = [NSPredicate predicateWithFormat:@"self.name IN {'小白', '小黑'} || self.age IN {79, 28}"];
filterArray = [persons filteredArrayUsingPredicate:predicate];
for (Person *p in filterArray) {
NSLog(@"pName : %@", p.name);
}
使用IN符號(hào)
predicate = [NSPredicate predicateWithFormat:@"name BEGINSWITH 'A'"]; filterArray = [persons filteredArrayUsingPredicate:predicate];
for (Person *p in filterArray) {
NSLog(@"pName : %@", p.name);
}
查找以字符''開頭的
predicate = [NSPredicate predicateWithFormat:@"name ENDSWITH 'A'"]; filterArray = [persons filteredArrayUsingPredicate:predicate];
for (Person *p in filterArray) {
NSLog(@"pName : %@", p.name);
}
查找以字符''結(jié)尾的
predicate = [NSPredicate predicateWithFormat:@"name CONTAINS 'a'"];
filterArray = [persons filteredArrayUsingPredicate:predicate];
for (Person *p in filterArray) {
NSLog(@"pName : %@", p.name);
}
查找包含字符''的
//like 匹配任意多個(gè)字符
//name中只要有s字符就滿足條件
predicate = [NSPredicate predicateWithFormat:@"name like '*s*'"];
//?代表一個(gè)字符,下面的查詢條件是:name中第二個(gè)字符是s的
predicate = [NSPredicate predicateWithFormat:@"name like '?s'"];
謂詞的使用很方便,和我們當(dāng)初在操作數(shù)據(jù)庫(kù)的時(shí)候很像,但是它對(duì)我們進(jìn)行過(guò)濾操作提供了很大的便捷。