#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self test3];
}
- (void)test3{
Person *p1 = [Person new];
p1.name = @"張三";
p1.age = 14;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.age > 15"];
//使用謂詞評估對象
BOOL result = [predicate evaluateWithObject:p1];
if (result) {
NSLog(@"大於15歲");
}else{
NSLog(@"小於15歲");
}
}
- (void)test2{
Person *p1 = [Person new];
p1.name = @"張三";
p1.age = 18;
Person *p2 = [Person new];
p2.name = @"李四";
p2.age = 17;
Person *p3 = [Person new];
p3.name = @"王五";
p3.age = 14;
Person *p4 = [Person new];
p4.name = @"張扇風";
p4.age = 20;
Person *p5 = [Person new];
p5.name = @"張點";
p5.age = 15;
NSArray *persons = @[p1,p2,p3,p4,p5];
//查找包含'張'的人
NSString *name = @"張三";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.name == %@",name];
NSArray *results = [persons filteredArrayUsingPredicate:predicate];
NSLog(@"%@",[results valueForKey:@"name"]);
for (Person *p in results) {
NSLog(@"%@",p.name);
}
}
- (void)test1{
NSArray *array = @[@"23451345",@"2222435",@"54674578",@"dryjtuj",@"467222"];
//篩選出字符串含有 "222" 的字符串
//謂詞(條件)-語句不區分大小寫
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self CONTAINS '222'"];
//使用謂詞去過濾
NSArray *results = [array filteredArrayUsingPredicate:predicate];
NSLog(@"%@",results);
}
@end
實用知識:NSPredicate(謂詞)的使用
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.