NSString拼接字符串和NSPredicate详解

NSString* string; // 结果字符串
02 NSString* string1, string2; //已存在的字符串,需要将string1和string2连接起来
03  
04 //方法1.
05 string = [[NSString alloc]initWithFormat:@"%@,%@", string1, string2 ];
06  
07 //方法2.
08 string = [string1 stringByAppendingString:string2];
09  
10 //方法3 .
11 string = [string stringByAppendingFormat:@"%@,%@",string1, string2];

经常用的是第二种方法。

NSPredicate类:主要用来指定过滤器的条件,该对象可以准确的描述所需条件,对每个对象通过谓词进行筛选,判断是否与条件相匹配。谓词是指在计算机中表示计算真假值的函数。原理和用法都类似于SQL查询中的where,作用相当于数据库的过滤取。主要用于从集合中分拣出符合条件的对象,也可以用于字符串的正则匹配


定义(最常用到的方法):

[plain] view plaincopy
  1. NSPredicate *ca = [NSPredicate predicateWithFormat:(NSString *), ...];  

例子1:

(1)对NSArray进行过滤 

[plain] view plaincopy
  1. NSArray *array = [[NSArray alloc]initWithObjects:@"beijing",@"shanghai",@"guangzou",@"wuhan", nil];    
  2. NSString *string = @"ang";    
  3. NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",string];    
  4. NSLog(@"%@",[array filteredArrayUsingPredicate:pred]);    

例子2:

[plain] view plaincopy
  1. #import <Foundation/Foundation.h>  
  2. @interface Person: NSObject{  
  3.     int pid;  
  4.     NSString *name;  
  5.     float height;  
  6. }  
  7. -(void) setPid: (int) pid;  
  8. -(void) setName: (NSString*) name;  
  9. -(void) setHeight: (float) height;  
  10. -(int) pid;  
  11. -(NSString*) name;  
  12. -(float) height;  
  13. @end  

[plain] view plaincopy
  1. #import "Person.h"  
  2.   
  3. @implementation Person  
  4. -(void) setPid: (int) p{  
  5.     pid=p;  
  6. }  
  7. -(void) setName: (NSString*) n{  
  8.     [n retain];  
  9.     [name release];  
  10.     name=n;  
  11. }  
  12. -(void) setHeight: (float) h{  
  13.     height=h;  
  14. }  
  15. -(int) pid{  
  16.     return pid;  
  17. }  
  18. -(NSString*) name{  
  19.     return name;  
  20. }  
  21. -(float) height{  
  22.     return height;  
  23. }  
  24. -(void) dealloc{  
  25.     [name release];  
  26.     [super dealloc];  
  27. }  
  28. @end  

[plain] view plaincopy
  1. int main(int argc, char *argv[])  
  2. {  
  3.     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
  4.     //实例化三个Person,并放入数组。  
  5.     NSMutableArray *array=[NSMutableArray arrayWithCapacity: 5];  
  6.     Person *person1=[[Person alloc] init];  
  7.     [person1 setPid: 1];  
  8.     [person1 setName: @"Name1"];  
  9.     [person1 setHeight: 168];  
  10.     [array addObject: person1];  
  11.     Person *person2=[[Person alloc] init];  
  12.     [person2 setPid: 2];  
  13.     [person2 setName: @"Name2"];  
  14.     [person2 setHeight: 178];  
  15.     [array addObject: person2];  
  16.     Person *person3=[[Person alloc] init];  
  17.     [person3 setPid: 3];  
  18.     [person3 setName: @"Name3"];  
  19.     [person3 setHeight: 188];  
  20.     [array addObject: person3];  
  21.     //创建谓词,条件是pid>1 并且height<188.0。其实谓词也是基于KVC 的,也就是如果pid 在person 的成员变量xxx 中,那么此处要写成xxx.pid>1。  
  22.     NSPredicate *pre = [NSPredicate predicateWithFormat:  
  23.                         @" pid>1 and height<188.0"];  
  24.     int i=0;  
  25.     for(;i<[array count];i++){  
  26.         Person *person=[array objectAtIndex: i];  
  27.         //遍历数组,输出符合谓词条件的Person 的name。  
  28.         if ([pre evaluateWithObject: person]) {  
  29.             NSLog(@"%@",[person name]);  
  30.         }  
  31.     }  
  32.     [person1 release];  
  33.     [person2 release];  
  34.     [person3 release];  
  35.     [pool release];  
  36.     return 0;  
  37. }  

我们看到创建谓词使用类方法predicateWithFormat: (NSString*) format,

format 里的东西真的和SQL 的where 条件差不多。

另外,参数format 与NSLog 的格式化模版差不多,如果1 和188.0 是传递过来的参数,你可以写成如下的形式:

@"pid>%d and height<%f",1,188.0
(1)比较运算符>,<,==
可用于数值及字符串
例:@"number > 100"
(1.) 逻辑运算符:AND、OR、NOT
这几个运算符计算并、或、非的结果。
(2.) 范围运算符:BETWEEN、IN
例:
@”pid BETWEEN {1,5}”
@"name IN {'Name1','Name2'}"
(3.) 占位符:
NSPredicate *preTemplate = [NSPredicate predicateWithFormat:@"name==$NAME"];
NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:
@"Name1", @"NAME",nil];
NSPredicate *pre=[preTemplate predicateWithSubstitutionVariables: dic];
占位符就是字段对象里的key,因此你可以有多个占位符,只要key 不一样就可以了。
(4.) 快速筛选数组:
前面我们都是使用谓词逐个判断数组内的对象是否符合,其实数组本身有更为便捷的方法,
直接筛选出一个符合谓词的新数组。
NSPredicate *pre = [NSPredicate predicateWithFormat:@"pid>1"];
NSMutableArray *arrayPre=[array filteredArrayUsingPredicate: pre];
NSLog(@"%@",[[arrayPre objectAtIndex: 0] name]);
(5.) 字符串运算符:
BEGINSWITH、ENDSWITH、CONTAINS 分别表示是否以某字符串开头、结尾、包含。
他们可以与c、d 连用,表示是否忽略大小写、是否忽略重音字母(字母上方有声调标号)。
例:
@”name BEGINSWITH[cd] ‘He’”
判断name 是否以He 开头,并且忽略大小写、忽略重音字母。
(6.) LIKE 运算符:
LIKE 使用?表示一个字符,*表示多个字符,也可以与c、d 连用。
例:
@”name LIKE ‘???er*’” 与Paper Plane 相匹配。
(7.) SELF:
前面的数组中放的都是对象,如果数组放的都是字符串(或者是其他没有属性的类型),该
怎么写谓词呢?这里我们使用SELF。
例:
NSArray *arrays=[NSArray arrayWithObjects: @"Apple", @"Google", @"MircoSoft", nil];
NSPredicate *pre2 = [NSPredicate predicateWithFormat:@"SELF=='Apple'"];
(8.) 正则表达式:
NSPredicate 使用MATCHES 匹配正则表达式,正则表达式的写法采用international components
for Unicode (ICU)的正则语法。
例:
NSString *regex = @"^A.+e$";//以A 开头,以e 结尾的字符。
NSPredicate *pre= [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
if([pre evaluateWithObject: @"Apple"]){
printf("YES\n");
}else{
printf("NO\n");
}


例子3:

一般来说这种情况还是蛮多的,比如你从文件中读入了一个array1,然后想把程序中的一个array2中符合array1中内容的元素过滤出来。

正 常傻瓜一点就是两个for循环,一个一个进行比较,这样效率不高,而且代码也不好看。

其实一个循环或者无需循环就可以搞定了,那就需要用搞 NSPredicate这个类了~膜拜此类~

1)例子一,一个循环

NSArray *arrayFilter = [NSArray arrayWithObjects:@"pict", @"blackrain", @"ip", nil];

NSArray *arrayContents = [NSArray arrayWithObjects:@"I am a picture.", @"I am a guy", @"I am gagaga", @"ipad", @"iphone", nil];

我想过滤arrayContents的话只要循环 arrayFilter就好了

int i = 0, count = [arrayFilter count];

for(i = 0; i < count; i ++)

{

NSString *arrayItem = (NSString *)[arrayFilter objectAtIndex:i];

NSPredicate *filterPredicate = [[NSPredicate predicateWithFormat:@"SELF CONTAINS %@", arrayItem];

NSLog(@"Filtered array with filter %@, %@", arrayItem, [arrayContents filteredArrayUsingPredicate:filterPredicate]);

}

当然以上代码中arrayContent最好用mutable 的,这样就可以直接filter了,NSArray是不可修改的。

2)例子二,无需循环

NSArray *arrayFilter = [NSArray arrayWithObjects:@"abc1", @"abc2", nil];

NSArray *arrayContent = [NSArray arrayWithObjects:@"a1", @"abc1", @"abc4", @"abc2", nil];

NSPredicate *thePredicate = [NSPredicate predicateWithFormat:@"NOT (SELF in %@)", arrayFilter];

[arrayContent filterUsingPredicate:thePredicate];


这样arrayContent过滤出来的就是不包含 arrayFilter中的所有item了。


3)生成文件路径下文件集合列表

NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *defaultPath = [[NSBundle mainBundle] resourcePath];
    NSError *error;
    NSArray *directoryContents = [fileManager contentsOfDirectoryAtPath:defaultPath error:&error]


4)match的用法

    1. 简单比较

    NSString *match = @"imagexyz-999.png";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF == %@", match];
    NSArray *results = [directoryContents filteredArrayUsingPredicate:predicate];
 
2. match里like的用法(类似Sql中的用法)
  NSString *match = @"imagexyz*.png";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF like %@", match];
    NSArray *results = [directoryContents filteredArrayUsingPredicate:predicate];
3. 大小写比较
  [c]表示忽略大小写,[d]表示忽略重音,可以在一起使用,如下:
NSString *match = @"imagexyz*.png";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF like[cd] %@", match];
    NSArray *results = [directoryContents filteredArrayUsingPredicate:predicate];
4.使用正则 
NSString *match = @"imagexyz-\\d{3}\\.png";  //imagexyz-123.png
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    NSArray *results = [directoryContents filteredArrayUsingPredicate:predicate];


总结:

1) 当使用聚合类的操作符时是可以不需要循环的

2)当使用单个比较类的操作符时可以一个循环来搞定

PS,例子 一中尝试使用[@"SELF CONTAINS %@", arrayFilter] 来过滤会挂调,因为CONTAINS时字符串比较操作符,不是集合操作符。







NSPredicate源代码:

[plain] view plaincopy
  1. #import <Foundation/NSObject.h>  
  2. #import <Foundation/NSArray.h>  
  3. #import <Foundation/NSSet.h>  
  4.   
  5. NS_CLASS_AVAILABLE(10_4, 3_0)  
  6. @interface NSPredicate : NSObject <NSCoding, NSCopying> {  
  7.     void *_reserved;  
  8. }  
  9. + (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat argumentArray:(NSArray *)arguments;  
  10. + (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat, ...;  
  11. + (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat arguments:(va_list)argList;  
  12.   
  13. + (NSPredicate *)predicateWithValue:(BOOL)value;     
  14.   
  15. #if NS_BLOCKS_AVAILABLE  
  16. + (NSPredicate*)predicateWithBlock:(BOOL (^)(id evaluatedObject, NSDictionary *bindings))block NS_AVAILABLE(10_6, 4_0);   
  17. #endif  
  18.   
  19. - (NSString *)predicateFormat;      
  20.   
  21. - (NSPredicate *)predicateWithSubstitutionVariables:(NSDictionary *)variables;      
  22.   
  23. - (BOOL)evaluateWithObject:(id)object;      
  24.   
  25. - (BOOL)evaluateWithObject:(id)object substitutionVariables:(NSDictionary *)bindings NS_AVAILABLE(10_5, 3_0);   
  26.   
  27. @end  
  28.   
  29. @interface NSArray (NSPredicateSupport)  
  30. - (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate;      
  31. @end  
  32.   
  33. @interface NSMutableArray (NSPredicateSupport)  
  34. - (void)filterUsingPredicate:(NSPredicate *)predicate;      
  35. @end  
  36.   
  37.   
  38. @interface NSSet (NSPredicateSupport)  
  39. - (NSSet *)filteredSetUsingPredicate:(NSPredicate *)predicate NS_AVAILABLE(10_5, 3_0);      
  40. @end  
  41.   
  42. @interface NSMutableSet (NSPredicateSupport)  
  43. - (void)filterUsingPredicate:(NSPredicate *)predicate NS_AVAILABLE(10_5, 3_0);      
  44. @end  

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/247914.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

线程模块

信号量 from threading import Semaphore,Thread import timedef func(a,b):time.sleep(1)sem.acquire()print(ab)sem.release()sem Semaphore(4) for i in range(10):t Thread(targetfunc,args(i,i5))t.start() 信号量事件 # 事件被创建的时候&#xff0c;默认为False状态 #…

React中级学习(第一天)

Props深入 children 作用 : 获取组件标签的 子节点获取方式 : this.props.children <App>此处的内容&#xff0c;就是组件的 children&#xff0c;将来通过组件的 props.children 就可以获取到这些子节点了 </App>props 校验 作用&#xff1a;规定组件props的类…

iOS 正则表达式判断纯数字以及匹配11位手机号码

1用正则表达式 //是否是纯数字(BOOL)isNumText:(NSString *)str{NSString * regex "(/^[0-9]*$/)";NSPredicate * pred [NSPredicate predicateWithFormat:"SELF MATCHES %", regex];BOOL isMatch [pred evaluateWithObject:st…

Elasticsearch集成ik分词器

1、插件地址https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.0.0/elasticsearch-analysis-ik-7.0.0.zip 2、找到对应版本的插件通过 http://192.168.1.8:9200查看ES的版本&#xff0c;找到对应的IK分词插件 下载与之对应的版本https://github.com/me…

React中级学习(第二天)

JSX 语法的转化过程 (了解) 演示 : babel中文网试一试 let h1 JSX 仅仅是createElement() 方法的语法糖 (简化语法)JSX 语法 被 babel/preset-react 插件编译为 createElement() 方法React 元素&#xff1a;是一个对象&#xff0c;用来描述你希望在屏幕上看到的内容React 元素…

【】MTCNN基于NCNN的测试过程

前言 操作过程 NCNN: https://github.com/Tencent/ncnn/wiki/how-to-build#build-for-linux-x86; vector初始化&#xff1a;int num[4] { 1, 4, 3, 2 }; int numLength sizeof(num) / sizeof(num[0]); vector<int> nums(num, num numLength); //使用数组初始化向量 Q&…

iOS NSTextAttachment - 图文混排

苹果在iOS7中推出了一个新的类NSTextAttachment&#xff0c;它是做图文混排的利器&#xff0c;本文就是用这个类&#xff0c;只用50行代码实现文字与表情混排&#xff0c;当然也可以实现段落中的图文混排。 首先说一下文字和表情的混排&#xff1a; 先来做点儿准备工作&#…

vuex的结构有哪些参数?

查看参考地址&#xff1a; https://vuex.vuejs.org/zh/ vuex 状态管理模式&#xff0c;相当于数据的中间商 注意&#xff1a; 为相同 属性有&#xff1a; 1.State vue中的data —> 存放数据 2.Getter vue中的计算属性computed —>将已有的数据进行计算再次利用 3.…

百炼OJ - 1004 - 财务管理

题目链接&#xff1a;http://bailian.openjudge.cn/practice/1004/ 思路 求和取平均。。。 #include <stdio.h>int main() {float sum0,a;for(int i0;i<12;i){scanf("%f",&a);sum a;}printf("$%.2f\n",sum/12);return 0; } 转载于:https://w…

iOS 自定义Cell按钮的点击代理事件

在实际开发工作中&#xff0c;我们经常会在自定义的Cell中布局一些按钮&#xff0c;并且很多时候我们会在点击这个按钮的时候使我们的UItableviewController跳转到下一界面&#xff0c;有的可能还要传值。那么如何使我们的控制器能够获知我们按下了cell的按钮呢&#xff1f;毫无…

Google 开源技术protobuf 简介与样例

今天来介绍一下“Protocol Buffers ”&#xff08;以下简称protobuf&#xff09;这个玩意儿。本来俺在构思“生产者/消费者模式 ”系列的下一个帖子&#xff1a;关于生产者和消费者之间的数据传输格式。由于里面扯到了protobuf&#xff0c;想想干脆单独开一个帖子算了。 ★prot…

VUE全局导航守卫、 请求、响应拦截器 的设置

文件设置参考地址&#xff1a;https://gitee.com/wang_yu5201314/headlines__news/tree/master/%E9%A1%B9%E7%9B%AE%E6%BA%90%E7%A0%81%E6%96%87%E4%BB%B6/src 文件夹 Router 文件夹 index.js 中设置 全局导航守卫 文件 mian.js 中设置 请求、响应拦截器 设置 请求、响应拦截器…

JRE System Library和 Referenced Libraries 的区别和来源

JRE System Library 安装jdk后&#xff0c;会有个目录叫做jrejre目录是核心类库&#xff0c;目录中装的是类库文件jre System Library顾名思义就表示系统类库文件 Referenced Libraries referenced libraries放的是你引用的jar包&#xff0c;这个不需要自己创建的&#xff0c;你…

ByteArray、16进制、字符串之间的转换

ByteArray、16进制、字符串之间的转换&#xff1a; package fengzi.convert {import flash.utils.ByteArray;public class ByteArrayTranslated{/**** 通过hax数据返回ByteArray* param hax 格式 "AA5A000100FF"***/public static functi…

js - (初中级)常见笔试面试题

1.用 js 实现一个深拷贝 2.用 js 写一个数组去重 3. 用 js 对字符串进行反转 4. 用 js 请求范围内的质数个数 5.用 js 求数组中出现最多的数及其出现次数

iOS 支付宝SDK接入详解

一&#xff0c;在支付宝开放平台下载支付宝SDK&#xff08;https://openhome.alipay.com/platform/document.htm#down&#xff09; https://doc.open.alipay.com/doc2/detail.htm?spma219a.7629140.0.0.HpDuWo&treeId54&articleId104509&docType1 二&#xff0c;添…

面试基本知识点

文章目录面-什么是SEO面 - cookie / localstorage / sessionstorage的区别面 - promise面试题面 - 柯里化函数面 - 函数节流面 - 函数防抖HTML / CSS 知识点1、讲讲盒模型&#xff08;蚂蚁金服 2019.03 招行信用卡 2019.04 美团 作业帮&#xff09;2、根据盒模型解释边距重叠&a…

Redis 热点key

压测报redis 热点问题 热点问题概述 产生原因 热点问题产生的原因大致有以下两种&#xff1a; 用户消费的数据远大于生产的数据&#xff08;热卖商品、热点新闻、热点评论、明星直播&#xff09;。 在日常工作生活中一些突发的的事件&#xff0c;例如&#xff1a;双十一期间某些…

移动IM开发那些事:技术选型和常见问题

最近在做一个iOS IM SDK&#xff0c;在内部试用的阶段&#xff0c;不断有兄弟部门或者合作伙伴过来问各种技术细节&#xff0c;所以统一写一篇文章记录&#xff0c;统一介绍下一个IM APP的方方面面&#xff0c;包括技术选型(包括通讯方式,网络连接方式,协议选择)和常见问题。 …

webstrom打开通过顶部浏览器打开网页,被跳转到默认主页

重新开始工作啦&#xff0c;希望以后认真一点&#xff0c;并把遇到的问题都记录下来&#xff0c;虽然是小小白&#xff0c;但能无意间帮助到别人就更开心了呀 通过webstrom打开本地的文件时&#xff0c;发现跳转到了默认主页上&#xff0c;吐槽下&#xff0c;有些主页真的超级流…