OC中的謂詞操作是針對于數組類型的,他就好比數據庫中的查詢操作,數據源就是數組,這樣的好處是我們不需要編寫很多代碼就可以去操作數組,同時也起到過濾的作用,我們可以編寫簡單的謂詞語句,就可以從數組中過濾出我們想要的數據。非常方便。
下面直接上代碼操作一下.
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
創建一個Person類,里面有_name和_age兩個屬性.
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];
創建一個數組,元素是Person *對象.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age<%d", 30];
NSArray *filterArray = [persons filteredArrayUsingPredicate:predicate];
創建一個謂詞,也就是一個篩選條件,即年齡在30以下的,并且創建一個新的數組fileArray來接受符合條件的元素.
predicate = [NSPredicate predicateWithFormat:@"age < %d && name = %@", 30, @"zhangsan"];
filterArray = [persons filteredArrayUsingPredicate:predicate];
for (Person *p in filterArray) {
NSLog(@"pName : %@", p.name);
}
當然也可以創建多個篩選條件的謂詞
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符號
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);
}
查找以字符''結尾的
predicate = [NSPredicate predicateWithFormat:@"name CONTAINS 'a'"];
filterArray = [persons filteredArrayUsingPredicate:predicate];
for (Person *p in filterArray) {
NSLog(@"pName : %@", p.name);
}
查找包含字符''的
//like 匹配任意多個字符
//name中只要有s字符就滿足條件
predicate = [NSPredicate predicateWithFormat:@"name like '*s*'"];
//?代表一個字符,下面的查詢條件是:name中第二個字符是s的
predicate = [NSPredicate predicateWithFormat:@"name like '?s'"];
謂詞的使用很方便,和我們當初在操作數據庫的時候很像,但是它對我們進行過濾操作提供了很大的便捷。