- 谓词在搜索的时候非常管用.简单示例代码如下:
- 分类Person.h文件
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age;
@end
- Person.m文件 重写一下description方法,输出打印时 便于观看
#import "Person.h"
@implementation Person
-(NSString *)description{
return [NSString stringWithFormat:@"%@ -- %d",_name,self.age];
}
@end
//
// ViewController.m
// 谓词练习
//
// Created by 裴波波 on 16/5/4.
// Copyright © 2016年 裴波波. All rights reserved.
//
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray * arrayM = [NSMutableArray array];
for (int i = 0; i< 50; i ++ ) {
Person * per = [Person new];
int age = arc4random_uniform(1456);
NSString * str = [NSString stringWithFormat:@"Tom%03d",age];
per.age = age;
per.name = str;
[arrayM addObject:per];
}
NSLog(@"%@",arrayM);
/**
&& 且
|| 或
! 非
比较运算符 例如:@"number >= 99"
< 小于
<= 小于等于
== 等于
> 大于
>= 大于等于
BETWEEN {a,b} 包含在区间 例:@"number BETWEEN {1,5}"
BEGANWITH:以指定字符开始 @"name BEGINSWITH[c] 'sh'" //以某个字符串开头
ENDSWITH:以指定字符结束 @"name ENDSWITH[d] 'ang'" //以某个字符串结束
CONTAINS:包含指定字符,可使用修饰符 @"name CONTAIN[cd] 'ang'" //包含某个字符串
c 不区分大小写
d 不区分注音符号
LIKE:使用通配符匹配 @"name LIKE[cd] '*er*'" *代表通配符,Like也接受[cd].
? 一个字符
* 0个或多个字符
*/
/** 使用谓词 */
// 条件为 name属性里面包含字符9的,并且age在区间100 ~ 500之间的 per输出打印出来
NSPredicate * p = [NSPredicate predicateWithFormat:@"name CONTAINS '9' && age BETWEEN {100,500}"];
NSArray *array = [arrayM filteredArrayUsingPredicate:p];
NSLog(@"%@",array);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end