結合之前的學習筆記以及參考《Objective-C程式設計全解(第三版)》,對Objective-C知識點進行梳理總結。知識點一直在變,僅僅是作為參考,以蘋果官方文檔為準~
十八、謂語的使用及執行個體說明
首先先介紹基本經常使用的謂詞:
(1)邏輯運算符 && AND || OR 都能夠用
(2)IN包括
(3)模糊查詢
a、以……開頭 BEGINSWITH
b、以……結尾 ENDSWITH
c、包括….字元 CONTAINS
(4)用like進行模糊查詢
通配符:*表示随意個字元 ?表示單個字元
like *a 以a結尾
like a* 以a開頭
like *a* 包括a字元
like ?a* 第二個字元為a的字元串
執行個體說明:
建立Book類,Book.h
@interface Book : NSObject
{
NSInteger _price;
NSString* _bookName;
}
- (instancetype)initWithPrice:(NSInteger)price andBookName:(NSString *)bookName;
@end
Book.h
#import "Book.h"
@implementation Book
- (instancetype)initWithPrice:(NSInteger)price andBookName:(NSString *)bookName {
if (self = [super init]) {
_price = price;
_bookName = bookName;
}
return self;
}
- (NSString *)description {
return [NSString stringWithFormat:@"Book price:%li,named %@",_price,_bookName];
}
@end
main.m
int main(int argc, const char * argv[]) {
@autoreleasepool {
Book* book1 = [[Book alloc] initWithPrice: andBookName:@"C Programming"];
Book* book2 = [[Book alloc] initWithPrice: andBookName:@"C++ Programming"];
Book* book3 = [[Book alloc] initWithPrice: andBookName:@"Java Programming"];
Book* book4 = [[Book alloc] initWithPrice: andBookName:@"OC guiding"];
Book* book5 = [[Book alloc] initWithPrice: andBookName:@"iOS guiding"];
NSArray* books = [NSArray arrayWithObjects:book1,book2,book3,book4,book5, nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"price > %i",];
NSArray *filterArray = [books filteredArrayUsingPredicate:predicate];
NSLog(@"%@",filterArray);
// 邏輯運算符 和 IN
predicate = [NSPredicate predicateWithFormat:@"bookName IN {'C Programming','C++ Programming'} AND price > 30"];
filterArray = [books filteredArrayUsingPredicate:predicate];
NSLog(@"%@",filterArray);
// 模糊查詢 和 用通配符查詢
predicate = [NSPredicate predicateWithFormat:@"bookName CONTAINS 'guiding' || bookName like '*Program*' "]; //包括guiding或者包括Program
filterArray = [books filteredArrayUsingPredicate:predicate];
NSLog(@"%@",filterArray);
}
return ;
}
output:
2015-07-09 20:17:24.403 exercise_謂語[632:9877] (
"Book price:32,named C++ Programming",
"Book price:45,named OC guiding"
)
2015-07-09 20:17:24.404 exercise_謂語[632:9877] (
"Book price:32,named C++ Programming"
)
2015-07-09 20:17:24.407 exercise_謂語[632:9877] (
"Book price:20,named C Programming",
"Book price:32,named C++ Programming",
"Book price:18,named Java Programming",
"Book price:45,named OC guiding",
"Book price:28,named iOS guiding"
)