objective-c 谓词 主要应用创建过滤。
#import <Foundation/Foundation.h>
@interface Person:NSObject
@property (copy)NSString *name;
@property int age;
@end
#import "Person.h"
@implementation Person
@synthesize name;
@synthesize age;
-(NSString *)description
{
NSString * des = [NSString stringWithFormat:@"name:%@ age:%d",name,age];
return des;
}
@end
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSMutableArray *persons = [[NSMutableArray alloc] init];
int i;
for(i = 0;i < 10 ;i++)
{
Person * person = [[Person alloc] init];
if(i < 5)
{
person.name = [NSString stringWithFormat:@"jack-%d",i];
}else{
person.name = [NSString stringWithFormat:@"tom-%d",i];
}
person.age = (20+i);
[persons addObject: person];
[person release];
}
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"name=='jack-4'"];//创建谓词判断属性
//比较和逻辑运算符
predicate=[NSPredicate predicateWithFormat:@"age>25 && age<27"];
//格式化说明符
predicate=[NSPredicate predicateWithFormat:@"name==%@",@"jack-4"];
predicate=[NSPredicate predicateWithFormat:@"age > %d",25];
predicate=[NSPredicate predicateWithFormat:@"%K > %d",@"age",25];
//数组运算符
NSArray *between = [NSArray arrayWithObjects:[NSNumber numberWithInt:25],[NSNumber numberWithInt:27],nil];
predicate=[NSPredicate predicateWithFormat:@"age BETWEEN %@",between];
predicate=[NSPredicate predicateWithFormat:@"name IN {'jack-2','tom'}"];
//字符串运算符
predicate=[NSPredicate predicateWithFormat:@"name BEGINSWITH 'ja'"];//已ja开头
predicate=[NSPredicate predicateWithFormat:@"name ENDSWITH '-5'"];//-5结尾
predicate=[NSPredicate predicateWithFormat:@"name CONTAINS '-'"];//包含-
//LIKE运算符
predicate=[NSPredicate predicateWithFormat:@"name LIKE '*ck*'"];
predicate=[NSPredicate predicateWithFormat:@"name LIKE '?a*'"];
//对数组过滤
NSArray * filterArray = [persons filteredArrayUsingPredicate:predicate];
NSLog(@"%@",filterArray);
}
return 0;
}