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.pswp.cn/news/247914.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/247914.shtml
英文地址,請注明出處:http://en.pswp.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;有些主頁真的超級流…