查找数组当中指定的信息([示例]NSPredicate基础-查询数组中符合条件的子集)

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        /*
         简述:Cocoa框架中的NSPredicate用于查询,原理和用法都类似于SQL中的where,作用相当于数据库的过滤取。
         定义(最常用到的方法):
         NSPredicate这个类有点类似于数据库中的查询,是用于在一批内容中查询符合条件的子集,中文翻译成“谓词”。这个翻译实在让我感觉很别扭,虽然明知道和谓语这个词语没什么关系,但确实总让我感觉这是一个句子里面的成分。
         我们有些时候会有一个对象的数组或者集合,然后希望从里面找出符合条件的集合,类似于做一次过滤操作。比如我有一批照片,希望能找出所有某一天里面拍摄的内容。
         NSPredicate类的创建往往使用predicateWithFormat的方法,这个方法的使用有点类似于stringWithFormat方法。
         */
        //查询数组中含有“ang”的字符串
        NSArray *array = [[NSArray alloc]initWithObjects:@"beijing",@"shanghai",@"guangzou",@"wuhan", nil];
        NSString *string = @"ang";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",string];
        NSLog(@"%@",[array filteredArrayUsingPredicate:pred]);    ;
        //查找名字里面包含“王”的姓
NSArray *array1 = [[NSArray alloc]initWithObjects:@"小王",@"王力",@"李丽",@"方方", nil]; NSString *match = @"*王*"; //查找姓王的名字,王字必须为首字则修改NSString *match=@"王*"; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF like %@", match]; NSArray *results = [array1 filteredArrayUsingPredicate:predicate]; for (id str in results) { NSLog(@"%@",str); } } return 0; }
原文地址:https://www.cnblogs.com/xzz5211314/p/5120149.html